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: 4
💡 Note: The subsequence [1,2,3,4] is valid: (1+2)%3=0, (2+3)%3=2, (3+4)%3=1. Wait, this doesn't work. Let me recalculate. Actually [1,4] works: we only have one pair (1+4)%3=2, so length=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
Find Maximum Length of Valid Subsequence IIInput: nums = [1,2,3,4], k = 31234Valid subsequences (consecutive pairs have same remainder):[1,4]: (1+4)%3 = 2 ✓ Length=2[2,3]: (2+3)%3 = 2 ✓ Length=2Maximum Valid Length = 2Output: 2
Understanding the Visualization
1
Input
Array nums and modulus k
2
Process
Find subsequence where consecutive pair sums have same remainder
3
Output
Length of longest valid subsequence
Key Takeaway
🎯 Key Insight: Use DP to track longest sequences by remainder pairs, avoiding exponential subsequence enumeration
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