Jump Game VI

MediumMonotonic Deque · Dynamic Programming🧩 Queue & Monotonic DequeLeetCode #1696 ↗Updated

Problem

You stand on index 0 of an integer array nums and must reach the last index. From index i you may jump forward to any index in [i + 1, i + k] (staying inside the array). Your score is the sum of nums over every index you land on, including the first and last. Return the maximum achievable score.
Inputnums = [1,-1,-2,4,-7,3], k = 2Output7 (1 → -1 → 4 → 3)
Inputnums = [10,-5,-2,4,0,3], k = 3Output17
Inputnums = [1,-5,-20,4,-1,3,-6,-3], k = 2Output0

1 ≤ n, k ≤ 105  ·  -104 ≤ nums[i] ≤ 104

Try it yourself

Java
class Solution {
    public int maxResult(int[] nums, int k) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
dp[i] = nums[i] + max(dp[i-k..i-1]) — a sliding window maximum over the dp array. A deque of indices with decreasing dp values gives that maximum in O(1) amortized per step.
PatternQueue & Monotonic Deque

Instinct Arrival order matters, or you need the max/min of a moving window - reach for a FIFO queue, or a deque of indices kept in sorted order.

Memory hack Old ones leave by the front door, weak ones get bounced out the back - so whoever stands at the front is always the champion.

Open the Queue & Monotonic Deque guide →

Approaches

Brute ForceDP, Scan the Last k Scores

Time O(n · k)Space O(n)

Let dp[i] be the best score that ends on index i. The previous landing spot is one of the k indices before it, so take the best of those and add nums[i].

Java
public int maxResult(int[] nums, int k) {
    int n = nums.length;
    int[] dp = new int[n];
    dp[0] = nums[0];
    for (int i = 1; i < n; i++) {
        int best = Integer.MIN_VALUE;
        for (int j = Math.max(0, i - k); j < i; j++) {
            best = Math.max(best, dp[j]);
        }
        dp[i] = nums[i] + best;
    }
    return dp[n - 1];
}

Correct recurrence, but n = k = 105 means 1010 steps.

At a glance

LevelApproachTimeSpace
Brute ForceDP, Scan the Last k ScoresO(n · k)O(n)
BetterDP + Max-Heap with Lazy RemovalO(n log n)O(n)
OptimalDP + Monotonic DequeO(n)O(n)
Common pitfalls
  • Greedily jumping to the nearest non-negative value — it can miss a better path.
  • Using an O(n·k) loop when k can be as large as n.
  • Storing dp values instead of indices in the deque — you can't tell when they expire.
Interview tips
  • Write the O(n·k) recurrence first, then say “it's a sliding-window max”.
  • Mention the heap as a stepping stone before the deque.
  • Point out the score fits in int: |sum| ≤ 104 · 105.
Pattern
Monotonic deque → DP whose transition is a max/min over the last k states.
My notes saved in this browser