This is the "Hard" version of the previous problem. In Find the Maximum Length of a Good Subsequence II, the constraints on and are much larger. You still need to find the longest subsequence with at most adjacent differences, but you must optimize the transitions to avoid complexity.
Snowflake uses this to evaluate a candidate's ability to optimize Dynamic Programming transitions. It tests your mastery of using auxiliary data structures (like Hash Maps or running maximums) to convert an solution into . It evaluations whether you can identify that for a fixed number of changes , you only need the "best previous length" from any number and the "best previous length" from the same number.
This problem uses DP with Optimization (Caching Maximums).
dp[val][j] which is the max length ending with value val and j changes.max_for_changes[j] which is the max length across any value with j changes.nums[i]:
new_len = dp[nums[i]][j] + 1.new_len = max_for_changes[j-1] + 1.dp[nums[i]][j] and max_for_changes[j] with the maximum of these options.nums = [1, 2, 1, 1, 3], .
dp[1][0] = 1, max[0] = 1.dp[2][0] = 1, max[0] = 1.new = max[0] + 1 = 2. dp[2][1] = 2, max[1] = 2.new = dp[1][0] + 1 = 2. dp[1][0] = 2, max[0] = 2.new = max(dp[1][1]+1, max[0]+1) = max(1, 3) = 3. dp[1][1] = 3, max[1] = 3.
The logic continues, achieving linear time per change count.max_for_changes array, which is the key to the optimization.Master the "Max of previous" optimization in DP. Whenever you find yourself writing a loop for p in 0...i-1 inside a DP, ask if you can replace that loop with a single lookup from a precomputed maximum or a Hash Map. This is the hallmark of a senior-level algorithmic candidate.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Find the Maximum Length of a Good Subsequence I | Medium | Solve | |
| Sum of Good Subsequences | Hard | Solve | |
| Delete and Earn | Medium | Solve | |
| Length of Longest Fibonacci Subsequence | Medium | Solve | |
| Longest Arithmetic Subsequence of Given Difference | Medium | Solve |