Jump Game VI — LeetCode 1696 Python Solution

MediumQueueArrayDynamic ProgrammingMonotonic QueueHeap (Priority Queue)
Problem
#1696
Reading time
2 min

The problem

You are given a 0-indexed integer array nums and an integer k. You are initially standing at index 0.

Example

Input
nums = [1,-1,-2,4,-7,3], k = 2
Output
7
Explanation
You can choose your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.

Python solution

Python
class Solution:
    def maxResult(self, nums: List[int], k: int) -> int:
        n = len(nums)
        f = [0] * n
        q = deque([0])
        for i in range(n):
            if i - q[0] > k:
                q.popleft()
            f[i] = nums[i] + f[q[0]]
            while q and f[q[-1]] <= f[i]:
                q.pop()
            q.append(i)
        return f[-1]

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Heap / Priority Queue

Keep only the best k elements, or always pull the smallest, in log time. LeetCode 1696. Jump Game VI is filed here because LeetCode tags it Heap (Priority Queue), which is the vocabulary this hub collects.

The heap / priority queue guide has the Python template for the pattern and the 163 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1696. Jump Game VI?
LeetCode 1696. Jump Game VI is rated Medium on LeetCode.
What is the time complexity of LeetCode 1696. Jump Game VI?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1696. Jump Game VI?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1696. Jump Game VI cover?
LeetCode 1696. Jump Game VI is tagged Queue, Array, Dynamic Programming, Monotonic Queue and Heap (Priority Queue) on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview