3202: Find-the-Maximum-Length-of-Valid-Subsequence-II
Medium
table of contents
The intuition for this algorithm is that since
(sub[0] + sub[1]) % k == (sub[1] + sub[2]) % k == ... == (sub[x - 2] + sub[x - 1]) % k
had to be true, that implies that the sum of any adjacent
values in a valid subsequence must be equal to a value
between 0
and k-1
inclusive.
Therefore, we can iterate through all possible values of
sums between 0
and k-1
inclusive and find
the maximum subsequence length given a possible
sum.
code
class Solution {
public:
int maximumLength(vector<int>& nums, int k) {
int ans = 0;
for (int& num : nums) {
%= k;
num }
<int> dp (k);
vectorfor (int i = 0; i < k; ++i) {
(dp.begin(), dp.end(), 0);
fillfor (int& num : nums) {
[num] = dp[(k + i - num) % k] + 1;
dp= max(ans, dp[num % k]);
ans }
}
return ans;
}
};