This is the generalized version of the previous problem. In Find the Maximum Length of Valid Subsequence II, a subsequence is valid if the sum of every adjacent pair modulo is the same constant. You are given an array and an integer , and you need to find the longest valid subsequence.
Uber and Google use this to test your mastery of Dynamic Programming. Unlike version I where , here can be larger, requiring a more robust DP approach. It evaluations whether you can define a 2D state that tracks the last element and the target sum, and whether you can optimize the transitions to avoid checks.
This problem is solved using Dynamic Programming.
dp[rem][target] as the maximum length of a subsequence ending with a number whose remainder is rem, where the target sum of adjacent pairs modulo is target.remX = X % k.T from 0 to .prevRem = (T - remX + k) % k.dp[remX][T] = dp[prevRem][T] + 1.dp table.nums = [1, 4, 2, 3], .
Target Sum :
rem=1. prevRem = (2-1) = 1. dp[1][2] = dp[1][2] + 1 = 1.rem=1. prevRem = (2-1) = 1. dp[1][2] = 1 + 1 = 2.rem=2. prevRem = (2-2) = 0. dp[2][2] = dp[0][2] + 1 = 1.rem=0. prevRem = (2-0) = 2. dp[0][2] = dp[2][2] + 1 = 2.
Final result is the max across all .dp[i][j] (indices), leading to complexity.In DP problems involving subsequences and modular sums, the "remainder" of the last element is almost always part of the state. If the condition involves pairs, the state must link the current remainder to the previous one via the condition (the target sum).
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find the Maximum Length of Valid Subsequence I | Medium | Solve | |
| Maximum Absolute Sum of Any Subarray | Medium | Solve | |
| Minimum Score Triangulation of Polygon | Medium | Solve | |
| Solving Questions With Brainpower | Medium | Solve | |
| Last Stone Weight II | Medium | Solve |