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.
Visualization
Tap to expand
Understanding the Visualization
1
Start with Empty Chain
Begin with no beads selected
2
Add Compatible Beads
For each bead, either extend same-color chains or start new colors
3
Track Color Changes
Count transitions and ensure they don't exceed k
4
Find Longest Chain
Return the maximum length across all valid chains
Key Takeaway
🎯 Key Insight: Use dynamic programming to efficiently track all possible good subsequences by maintaining states for (changes_used, last_value) pairs, allowing us to build the optimal solution incrementally.
Time & Space Complexity
Time Complexity
O(n * k * unique_values)
For each position, we check all possible previous values and change counts
✓ Linear Growth
Space Complexity
O(k * unique_values)
DP table storing states for changes and values
⚡ Linearithmic Space
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code