Find the Maximum Length of Valid Subsequence II - DP [JS]
Solution: DP
For every value i
from 0
to k - 1
, use DP to count the longest subsequence where each adjacent pair (sub[i] + sub[i + 1]) % k === i
.
Each dp[mod]
= the longest subsequence length ending with each mod value mod
.
Time Complexity: O(nk)
Space Complexity: O(k)
function maximumLength(nums, k) {
let ans = 0;
for (let i = 0; i < k; i++) {
let dp = Array(k).fill(0);
for (let num of nums) {
let mod = num % k;
dp[mod] = Math.max(dp[mod], 1 + dp[(i - mod + k) % k]);
}
ans = Math.max(ans, Math.max(...dp));
}
return ans;
};
Comments
Post a Comment