Find the Maximum Length of a Good Subsequence I - Problem

You are given an integer array nums and a non-negative integer k.

A subsequence is called "good" if there are at most k positions where consecutive elements in the subsequence are different. In other words, if seq[i] != seq[i+1] for at most k indices i.

Your goal is to find the maximum possible length of a good subsequence from the given array.

Example: If nums = [1,2,1,1,3] and k = 2, you could choose subsequence [1,1,1,3] which has 2 transitions (1→1: no transition, 1→1: no transition, 1→3: transition), totaling 1 transition ≤ 2, so it's valid with length 4.

Input & Output

example_1.py — Basic Case
$ Input: nums = [1,2,1,1,3], k = 2
Output: 4
💡 Note: We can choose subsequence [1,1,1,3]. This has transitions: 1→1 (same), 1→1 (same), 1→3 (different). Only 1 transition ≤ 2, so it's valid with length 4.
example_2.py — No Changes Allowed
$ Input: nums = [1,2,3,4,5], k = 0
Output: 1
💡 Note: With k=0, we cannot have any transitions. We can only choose subsequences with identical elements. The longest such subsequence has length 1.
example_3.py — Many Changes Allowed
$ Input: nums = [1,2,1,1,3], k = 10
Output: 5
💡 Note: With k=10, we have more than enough changes allowed. We can take the entire array [1,2,1,1,3] which has 3 transitions, well within the limit.

Constraints

  • 1 ≤ nums.length ≤ 500
  • 1 ≤ nums[i] ≤ 103
  • 0 ≤ k ≤ min(nums.length, 25)
  • Note: The constraint on k being at most 25 makes the DP approach very efficient

Visualization

Tap to expand
Maximum Length of Good Subsequence INPUT nums array: 1 i=0 2 i=1 1 i=2 1 i=3 3 i=4 Input Values: nums = [1,2,1,1,3] k = 2 Good Subsequence: At most k positions where consecutive elements differ Goal: Find max length of such subsequence ALGORITHM STEPS (DP) 1 Define DP State dp[i][j] = max length ending at i with j differences 2 Initialize dp[i][0] = 1 for all i (single element, 0 diff) 3 Transition If nums[i]==nums[j]: extend without diff Else: use 1 diff slot 4 Track Maximum Update max length at each state DP Optimization: Track best endings by value Time: O(n^2 * k) FINAL RESULT Good Subsequence Found: 1 2 1 1 3 Differences between consecutive: diff same same Output: 4 Verification: Subsequence: [1,2,1,1] Differences: 1 (at pos 0-1) 1 <= k=2 --> OK Key Insight: The DP tracks subsequences by their ending value and number of "differences" used. When extending, if values match, no difference is consumed. Otherwise, we use one of our k allowed differences. This lets us efficiently find the longest subsequence with at most k transitions. TutorialsPoint - Find the Maximum Length of a Good Subsequence I | DP Approach
Asked in
Google 25 Amazon 18 Meta 12 Microsoft 8
28.5K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen