Problem Description
Given an integer array nums and an integer k, return the maximum sum of a non-empty subsequence of the array such that for every two consecutive integers in the subsequence, with indices i and j (i < j), the condition j - i <= k holds. A subsequence is formed by deleting some (or no) numbers from the array while keeping the order of the remaining elements.
Key Insights
- Use dynamic programming where dp[i] represents the maximum sum of a valid subsequence ending at index i.
- For each index i, consider taking nums[i] alone or appending it to a valid subsequence ending at an index j (where i - j <= k) that maximizes the sum.
- To efficiently obtain the maximum dp[j] in a sliding window of the last k indices, use a monotonic (decreasing) deque.
- The idea is to maintain the window maximum and update it as we proceed through the array.
Space and Time Complexity
Time Complexity: O(n)
Space Complexity: O(n) (O(k) extra space for the deque, with dp array using O(n))
Solution
We solve the problem by defining a dp array where dp[i] = nums[i] + max(0, maximum dp value in the window [i-k, i-1]). The trick is to include max(0, ...) to allow starting a new subsequence when previous sums are negative.
To access the maximum dp in the window in constant time, a monotonic deque is maintained that stores indices with their dp values in decreasing order.
At each index, we:
- Remove elements from the front of the deque if they are out of the current window (i - index > k).
- Use the front of the deque (if non-empty) as the maximum dp value from the previous k indices.
- Compute dp[i] and update the global maximum answer.
- Remove from the back of the deque all indices with dp values less than the current dp[i] since they are not useful.
- Insert the current index into the deque.