In the Find the Maximum Length of a Good Subsequence I coding problem, a subsequence is called "good" if the number of indices such that is at most . You are given an array of integers and an integer , and you need to find the length of the longest good subsequence.
Snowflake asks this to test your proficiency with Dynamic Programming interview patterns. It evaluations whether you can define a state that captures both the current element being considered and the number of "changes" used so far. It’s a test of how you handle transitions where you either continue a sequence of identical numbers or start a new sequence at the cost of one "change."
This problem is solved using Dynamic Programming.
dp[i][j] as the maximum length of a good subsequence ending at index i with exactly j changes.nums[i] to a subsequence ending at some p < i:
nums[i] == nums[p], the number of changes doesn't increase: dp[i][j] = max(dp[i][j], dp[p][j] + 1).nums[i] != nums[p], the number of changes increases by 1: dp[i][j] = max(dp[i][j], dp[p][j-1] + 1).dp table.nums = [1, 2, 1, 1, 3], .
[1, 1, 1] (0 changes, length 3).[1, 1, 1, 3] (1 change at the end, length 4).[1, 2, 1, 1] (1 change after '2', length 4).
Max length: 4.p inside the j loop, which is . While acceptable for Version I, it’s not optimal.dp table with 1 (since any single element is a valid subsequence of length 1 with 0 changes).When a problem involves a "at most changes" or "at most exceptions" constraint, it almost always points to a DP state where is one of the dimensions. Practice optimizing these DP transitions using running maximums or Hash Maps to achieve better complexity.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Delete and Earn | Medium | Solve | |
| Find the Maximum Length of a Good Subsequence II | Hard | Solve | |
| Length of Longest Fibonacci Subsequence | Medium | Solve | |
| Longest Arithmetic Subsequence of Given Difference | Medium | Solve | |
| Sum of Good Subsequences | Hard | Solve |