15% off all plans & roadmaps Use code

See plans

Jump Game VI

Updated

TL;DR: Start at index 0, jump at most k steps at a time, and maximise the sum of the values you land on. The winning idea is a DP whose window maximum comes from a monotonic deque, which runs in O(n).

Problem

You are given a 0-indexed integer array nums and an integer k.

You start at index 0. In one move, you can jump at most k steps forward without leaving the array. From index i, you can jump to any index in the range [i + 1, min(n - 1, i + k)], both ends included.

You want to reach the last index, n - 1. Your score is the sum of nums[j] for each index j you visit. Return the maximum score you can get.

Example 1

Input: nums = [1,-1,-2,4,-7,3], k = 2
Output: 7
Explanation: You can choose jumps that form the subsequence [1,-1,4,3]. The sum is 7.

Example 2

Input: nums = [10,-5,-2,4,0,3], k = 3
Output: 17
Explanation: You can choose jumps that form the subsequence [10,4,3]. The sum is 17.

Example 3

Input: nums = [1,-5,-20,4,-1,3,-6,-3], k = 2
Output: 0

Constraints

  • 1 <= nums.length, k <= 10^5
  • -10^4 <= nums[i] <= 10^4

Constraints that matter

  • The brute force does up to n * k work, and both n and k reach 10^5. You need work close to O(n) or O(n log n).
  • Values reach 10^4 in size, so any total stays within about 10^9 in size. That fits in a 32-bit int, so no 64-bit type is needed.
  • Scores can be negative, so you cannot skip a negative value. The best value in a window can itself be negative.
  • Since k is at least 1, every index after 0 has at least one predecessor. The window is never empty when you read it.

View on LeetCode

Hints

Hint 1

Let dp[i] be the best score you can hold when you land on index i.

Hint 2

Compute the scores in order.

Solution

Intuition

Let dp[i] be the best score you can hold when you land on index i. You can reach i from any index j in the previous k positions, so dp[i] = nums[i] + the largest dp[j] for j from i - k to i - 1. This is dynamic programming where each state depends on a sliding window of earlier states. The pattern is a sliding window maximum.

Picture a line at a ticket counter where a newcomer who scores at least as high makes every weaker person already waiting irrelevant. The deque is that line: its front is the best candidate still inside the window, and new arrivals join at the back.

What to notice: the window moves one step right for each new index. A fresh scan costs O(k) per index, and most of that work repeats the scan for the previous index. A window maximum that moves in one direction is the monotonic queue case. The queue keeps only the indices that could still be the maximum.

A monotonic stack does not fit here. A stack removes only from its top, but the window also loses its oldest index from the bottom. A deque supports removal at both ends, so it handles both events in constant time each.

Watch the pattern animation

Worked example

Input: nums = [1, -1, -2, 4, -7, 3], k = 2
Output: 7
Explanation: Jump from index 0 to 1, from 1 to 3, then from 3 to 5. The visited values are 1, -1, 4 and 3, which sum to 7. Indices 2 and 4 are skipped, and skipping the -2 and the -7 keeps the total high.

Approach 1: Brute force DP

Compute the scores in order. For each index i, look at every index the jump could come from. Those are the k indices before i, clamped at 0.

Keep the best score you see, add nums[i], and store the result. This is a direct translation of the recurrence, so a beginner writes it first.

The cost is in the repeated scans. The window for index i and the window for index i + 1 share almost all their indices, yet the loop compares them all again. With n and k both near 10^5, the loops reach billions of comparisons.

Steps

  1. Create dp with n slots and set dp[0] = nums[0].
  2. For each i from 1 to n - 1, set lo = max(0, i - k).
  3. Set best = dp[lo], then scan j from lo + 1 to i - 1 and keep the largest dp[j].
  4. Set dp[i] = nums[i] + best.
  5. Return dp[n - 1].

Dry run

Trace on the example nums = [1, -1, -2, 4, -7, 3] with k = 2. The window for each i is from max(0, i - 2) to i - 1.

  • dp[0] = 1.
  • i = 1: window [0, 0], best 1, dp[1] = -1 + 1 = 0.
  • i = 2: window [0, 1], best max(1, 0) = 1, dp[2] = -2 + 1 = -1.
  • i = 3: window [1, 2], best max(0, -1) = 0, dp[3] = 4 + 0 = 4.
  • i = 4: window [2, 3], best max(-1, 4) = 4, dp[4] = -7 + 4 = -3.
  • i = 5: window [3, 4], best max(4, -3) = 4, dp[5] = 3 + 4 = 7.

The answer is dp[5] = 7.

Complexity

TimeO(n * k)
SpaceO(n)

Let n be the length of nums. For index i, the inner loop runs min(i, k) times, because the window is clamped at 0. Summed over all i, the total work is at most n * k.

When k is close to n, this is O(n^2). The dp array holds n values, so space is O(n).

PythonTested in our runner

from typing import List, Optional

class Solution:
    def maxResult(self, nums: List[int], k: int) -> int:
        n = len(nums)
        dp = [0] * n
        dp[0] = nums[0]
        for i in range(1, n):
            lo = max(0, i - k)  # clamp so the index never wraps to the end
            best = dp[lo]
            for j in range(lo + 1, i):
                best = max(best, dp[j])
            dp[i] = nums[i] + best
        return dp[n - 1]

The Monotonic Queue for Max/Min infographic is part of Pro

A one-page visual of the pattern: when it applies, the steps and the invariant to keep.

Unlock the infographic

Solution pattern

Monotonic Queue for Max/Min

Part of Sliding Window

Approach 2: One-pass monotonic dequeOptimalMonotonic Queue for Max/Min

What's slow: the brute force rescans the window for each index, even though the window changes only at its two ends. Each step adds one new dp value on the right and drops at most one index on the left. Keep the candidates in a deque, so the best one is always at the front.

The insight that fixes it: if an older index j has a score no larger than a newer index m, then j is never needed again. Index m is later, so it leaves the window later. It also scores at least as well. Any future index that could jump from j can jump from m instead, so you can pop j at once.

The deque therefore holds indices in increasing order with strictly decreasing dp values. Its front is the best live candidate, which is the window maximum. For each i, drop an expired front, read the front, pop weaker values from the back, and then push i. The deque is never empty at the read, because index i - 1 is always in the window when k is at least 1.

Steps

  1. Set dp[0] = nums[0] and push index 0 onto the deque.
  2. For each i from 1 to n - 1, remove the front index if it is less than i - k.
  3. Set dp[i] = nums[i] + dp[front]. The front holds the best score in the window.
  4. Remove indices from the back while dp[back] is at most dp[i].
  5. Push i onto the back.
  6. Return dp[n - 1].

Dry run

Trace on the example nums = [1, -1, -2, 4, -7, 3] with k = 2. The deque is shown as index:score pairs after the push.

iexpiry checkdp[i] = nums[i] + dp[front]popped from backdeque after push
startnonedp[0] = 1none0:1
1front 0, is 0 < -1? no-1 + 1 = 0none, since 1 > 00:1, 1:0
2front 0, is 0 < 0? no-2 + 1 = -1none, since 0 > -10:1, 1:0, 2:-1
3front 0, is 0 < 1? yes, pop front4 + 0 = 42:-1 and 1:03:4
4front 3, is 3 < 2? no-7 + 4 = -3none, since 4 > -33:4, 4:-3
5front 3, is 3 < 3? no3 + 4 = 74:-3 and 3:45:7

The loop ends with dp[5] = 7, so the answer is 7. Each index was pushed once and popped at most once.

Complexity

TimeO(n)
SpaceO(n)

Let n be the length of nums. Each index is pushed once and popped at most once, either from the front or the back. Each loop iteration does constant work plus its pops, and the pops add up to at most n, so time is O(n).

The dp array holds n values and the deque holds at most k indices, so space is O(n).

PythonTested in our runner

from typing import List, Optional
from collections import deque

class Solution:
    def maxResult(self, nums: List[int], k: int) -> int:
        n = len(nums)
        dp = [0] * n
        dp[0] = nums[0]
        window = deque([0])  # indices, with dp values strictly decreasing
        for i in range(1, n):
            if window[0] < i - k:  # the front index has expired
                window.popleft()
            dp[i] = nums[i] + dp[window[0]]
            while window and dp[window[-1]] <= dp[i]:
                window.pop()
            window.append(i)
        return dp[n - 1]

Common mistakes

  • The read comes before the expiry check, as in dp[i] = nums[i] + dp[window[0]] placed above if window[0] < i - k. The read then uses an index more than k steps back. Pop the expired front first, then read the front.
  • The push comes before the read, so window.append(i) sits above dp[i] = .... The read can then pick index i itself, which still holds an unset value. Read the front first, clean the back, then push i.
  • The deque stores dp values instead of indices. Without indices you cannot tell whether the front has expired. Store indices and look up dp[index] each time.
  • The expiry test is off by one, for example window[0] < i - k - 1. That keeps an index k + 1 steps behind, which is one step too far. Pop only when the index is less than i - k.
  • A monotonic stack replaces the deque. A stack removes only from its top, so an expired index at the bottom can never be dropped. The stale best value then keeps being used. Use a deque that pops from both ends.
  • The brute force reads dp[i - k] with no lower bound. For i less than k, Python reads from the end of the list and raises no error. Start the scan at max(0, i - k).

Edge cases

  • n = 1, for example nums = [5] with k = 3. The loop never runs, and the answer is 5.
  • k = 1, for example nums = [1, 2, 3]. Every index must be visited, so the answer is 6, the plain sum.
  • All values negative, for example nums = [-1, -2, -3] with k = 2. Jumping from index 0 straight to index 2 scores -4, which beats -6 through index 1. The answer is -4.
  • k at least n, for example nums = [3, -10, 4] with k = 5. You can jump straight to the end, so the answer is 7, not -3.
  • Largest values, with every nums[i] = 10^4 and n = 10^5. The answer is 10^9, which fits in a 32-bit int.
  • Window boundary, for example k = 2 at i = 4. Index 2 equals i - k and is still in range, so it must be considered.

Follow-ups interviewers ask

Follow-ups are part of Pro

The questions interviewers ask after you solve Jump Game VI, with how to answer them.

Unlock the follow-ups

Jump Game VI FAQ

What is the time complexity of Jump Game VI?

The optimal solution runs in O(n) time, where n is the length of nums. Each index enters and leaves the deque at most once. The brute force scan runs in O(n * k) time.

Why use a monotonic deque for Jump Game VI?

Each dp value is the maximum of the previous k dp values, which is a sliding window maximum. A monotonic deque returns that maximum in amortised O(1) time. It also drops expired indices from the old end.

Can Jump Game VI be solved in O(1) extra space?

Not with this technique. The window must remember up to k candidates, so the deque needs O(k) space. Writing dp into nums removes the separate dp array but does not remove the deque.

Why not use a monotonic stack for Jump Game VI?

A stack removes only from the top. The window also has to drop its oldest index from the bottom once it is more than k steps back. A deque supports removal at both ends, so it fits the problem.

Does Python negative indexing cause a bug here?

Yes, in the brute force. When i is less than k, dp[i - k] reads from the end of the list without an error. Clamp the lower bound with max(0, i - k). The deque version never uses a negative index.

Asked at

See which companies ask this — Pro

Practise it