Find the Maximum Length of Valid Subsequence II - Problem

You are given an integer array nums and a positive integer k.

A subsequence sub of nums with length x is called valid if it satisfies:

(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k

Return the length of the longest valid subsequence of nums.

Input & Output

Example 1 — Basic Valid Subsequence
$ Input: nums = [1,2,3,4], k = 3
Output: 2
💡 Note: The longest valid subsequence has length 2. For example, [1,4] where (1+4)%3=2, or [2,3] where (2+3)%3=2.
Example 2 — Single Element
$ Input: nums = [1], k = 2
Output: 1
💡 Note: Single element subsequence [1] is valid by definition, length=1
Example 3 — Multiple Valid Pairs
$ Input: nums = [1,2,1,2], k = 2
Output: 4
💡 Note: The subsequence [1,2,1,2] is valid: (1+2)%2=1, (2+1)%2=1, (1+2)%2=1. All consecutive pairs have same remainder.

Constraints

  • 1 ≤ nums.length ≤ 103
  • 1 ≤ nums[i] ≤ 106
  • 2 ≤ k ≤ 103

Visualization

Tap to expand
Maximum Length of Valid Subsequence II INPUT nums array: 1 i=0 2 i=1 3 i=2 4 i=3 k = 3 k = 3 Valid Condition: (sub[i]+sub[i+1])%k == constant (1+2)%3=0, (2+3)%3=2 (3+4)%3=1, (4+1)%3=2 Need same remainder! ALGORITHM STEPS 1 Initialize DP dp[val%k][r] = max length 2 For each num Try all remainders 0 to k-1 3 Compute prev prev = (r - num%k + k) % k 4 Update DP dp[num%k][r] = dp[prev][r]+1 DP State: dp[val%k][remainder] r=0 r=1 r=2 v%k=0: 1 1 1 v%k=1: 2 2 2 v%k=2: 1 1 2 Max in table = answer FINAL RESULT Valid Subsequence Found: 1 2 3 4 0 2 1 (1+2)%3=0, (2+3)%3=2 (3+4)%3=1 All 4 elements work! The entire array is valid Output: 4 OK Key Insight: The DP state dp[v][r] tracks the max subsequence length ending with a value congruent to v (mod k), where consecutive pairs sum to r (mod k). For each new number, we check all k possible remainders and extend from the best previous state. Time: O(n*k), Space: O(k^2) - much better than O(n^2)! TutorialsPoint - Find the Maximum Length of Valid Subsequence II | Optimized DP with Better State Management
Asked in
Google 25 Meta 20 Amazon 18 Microsoft 15
12.5K Views
Medium Frequency
~35 min Avg. Time
450 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