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
Find Maximum Length of Good Subsequence INPUT Array nums: 1 i=0 2 i=1 1 i=2 1 i=3 k = 1 Good subsequence: At most k positions where seq[i] != seq[i+1] 1-->2-->1-->1 (1 change) ALGORITHM STEPS 1 Init DP Map dp[j][v] = max length ending at value v with j changes 2 Track Max Lengths mx[j] = global max for j changes (for O(1) lookup) 3 Process Each Num Same value: dp[j][v]+1 Diff value: mx[j-1]+1 4 Update States Update dp[j][v] and mx[j] Return max(mx[0..k]) Hash Map State dp[0][1]=1 dp[0][2]=1 dp[0][1]=3 (after 1,1,1) dp[1][1]=4 (1,2,1,1) mx[0]=3, mx[1]=4 FINAL RESULT Maximum Good Subsequence: 1 2 1 1 != == == Only 1 position where values differ (between index 0 and 1) Output: 4 OK - Length = 4 All 4 elements form a valid good subsequence Key Insight: Use Hash Map to track dp[j][v] = max length ending at value v with exactly j transitions where adjacent values differ. Maintain mx[j] = max over all values for j changes. This allows O(1) lookup for transitions, achieving O(nk) time complexity. For same value: extend without using a change. For different value: use mx[j-1] and add one change. TutorialsPoint - Find the Maximum Length of a Good Subsequence II | Optimized DP with Hash Map
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