Find the Maximum Length of a Good Subsequence II - Problem

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

A sequence of integers seq is called good if there are at most k indices i in the range [0, seq.length - 2] such that seq[i] != seq[i + 1].

Return the maximum possible length of a good subsequence of nums.

Input & Output

Example 1 — Basic Good Subsequence
$ Input: nums = [1,2,1,1], k = 1
Output: 4
💡 Note: The entire array [1,2,1,1] forms a good subsequence with exactly 1 transition: 1≠2 at position 0. All other adjacent pairs are equal (2≠1 at position 1 is not counted since we can choose the subsequence [1,1,1,1] by skipping index 1, but the full array gives length 4).
Example 2 — Limited Transitions
$ Input: nums = [1,2,3,4,5], k = 2
Output: 3
💡 Note: Best subsequence is [1,2,3] with 2 transitions: 1≠2 and 2≠3. We cannot include more elements without exceeding k=2 transitions.
Example 3 — No Transitions Allowed
$ Input: nums = [1,2,1,1,3], k = 0
Output: 3
💡 Note: With k=0, no adjacent elements can be different. Best subsequence is [1,1,1] with length 3 (all same elements).

Constraints

  • 1 ≤ nums.length ≤ 5000
  • -109 ≤ nums[i] ≤ 109
  • 0 ≤ k ≤ min(nums.length, 25)

Visualization

Tap to expand
Good Subsequence Problem: [1,2,1,1], k=11211i=0i=1i=2i=3==Transition count: 1≠2 (1 transition) ≤ k=1 ✓Full subsequence [1,2,1,1] is validMaximum Length: 4
Understanding the Visualization
1
Input Analysis
Array [1,2,1,1] with k=1 allowed transitions
2
Count Transitions
Track adjacent differences in potential subsequences
3
Find Maximum
Return length of longest valid subsequence
Key Takeaway
🎯 Key Insight: Use dynamic programming to track subsequences by ending value and transition count
Asked in
Google 25 Meta 18 Amazon 15 Microsoft 12
23.4K Views
Medium Frequency
~35 min Avg. Time
876 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