Find the Maximum Length of Valid Subsequence II - DP [JS]

Description 

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

Popular posts from this blog

Maximum Value of an Ordered Triplet II - Two Solutions [JS]

Maximum Sum of Distinct Subarrays With Length K - Sliding Window w/ Two Pointers & Set [JS]

Sum of Prefix Scores of Strings - Trie [JS]

Maximum Count of Positive Integer and Negative Integer - Binary Search [JS]

Count Subarrays With Median K - Count Left & Right Balance [JS]