AlgoInsight

DSA problem

Jump Game VI

MediumMonotonic QueuePattern: Monotonic Queuetop300AmazonGoogleMicrosoftMetaBloomberg

You are given a 0-indexed integer array nums and an integer k. You start at index 0, and from any index i you may jump to any index in the range [i + 1, i + k] as long as it stays within the array. Your score is the sum of all nums[j] for the indices j you land on, including the starting index 0 and the final index n - 1. Return the maximum score you can obtain by reaching the last index.

This is naturally a dynamic programming problem. Define dp[i] as the best score achievable when standing on index i. The recurrence is dp[i] = nums[i] + max(dp[i - k], dp[i - k + 1], …, dp[i - 1]). A direct evaluation costs O(n * k) because each state inspects up to k previous states, which is too slow when both n and k reach 10^5.

The bottleneck is the sliding-window maximum over the most recent k DP values. This is exactly what a monotonic deque solves in amortized constant time per step. We maintain a deque of indices into dp whose values are kept in strictly decreasing order from front to back. The front of the deque is always the index of the maximum DP value within the current window of size k.

The optimal algorithm walks left to right computing each dp[i] using dp[front] as the window maximum, then enqueues i after evicting all back indices whose DP values are not greater than dp[i]. Indices that fall out of the window (i.e. front < i - k + 1 shifted appropriately) are removed from the front. The answer is dp[n - 1]. The total work is O(n) time and O(n) space.

Examples

Example 1
Input: nums = [1,-1,-2,4,-7,3], k = 2
Output: 7
Explanation: A path that yields the maximum 7 is 0 -> 1 -> 3 -> 5 with values 1, -1, 4, 3. Each jump moves at most 2 indices, and 1 + (-1) + 4 + 3 = 7.
Example 2
Input: nums = [10,-5,-2,4,0,3], k = 3
Output: 17
Explanation: One optimal path is 0 -> 3 -> 5 with values 10, 4, 3, summing to 17. All jumps stay within range 3.
Example 3
Input: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2
Output: 0
Explanation: The best path 0 -> 1 -> 3 -> 5 -> 7 collects values 1, -5, 4, 3, -3 with sum 0. No alternative does better given the window limit of 2.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

dynamic-programmingmonotonic-queuesliding-windowarray

Browse all DSA problems