Constrained Subsequence Sum
HardDynamic Programmingmonotonic queue
Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.
Practice this as a mock interviewFree to start, no account neededProblem
Given an integer array nums and an integer k, choose a non-empty subsequence (keep elements in their original order) such that for every two consecutive chosen elements at indices i < j, the gap satisfies j - i <= k.
Return the maximum possible sum of such a subsequence.
Aim for O(n) time.
Examples
Input: nums = [10,2,-10,5,20], k = 2
Output: 37
Pick 10, 2, 5, 20; no two consecutive picks are more than 2 apart.
Input: nums = [-1,-2,-3], k = 1
Output: -1
The subsequence must be non-empty, so take just -1.
Input: nums = [10,-2,-10,-5,20], k = 2
Output: 23
Pick 10, -2, -5, 20 so that each gap is at most 2.
Constraints
- 1 <= k <= nums.length <= 10^5
- -10^4 <= nums[i] <= 10^4
What the interviewer grades
A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.