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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code