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:
3
💡 Note:
The best subsequence is [1,1,1] (taking elements at indices 0,2,3) with 0 transitions, giving length 3. We cannot take the full array [1,2,1,1] as it would have 2 transitions (1≠2 and 2≠1), exceeding k=1.
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code