Skip to content

1696. Jump Game VI 👍

  • Time: $O(n)$
  • Space: $O(n)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
 public:
  int maxResult(vector<int>& nums, int k) {
    // Stores dp[i] within the bounds.
    deque<int> maxQ{0};
    // dp[i] := the maximum score to consider nums[0..i]
    vector<int> dp(nums.size());
    dp[0] = nums[0];

    for (int i = 1; i < nums.size(); ++i) {
      // Pop the index if it's out-of-bounds.
      if (maxQ.front() + k < i)
        maxQ.pop_front();
      dp[i] = dp[maxQ.front()] + nums[i];
      // Pop indices that won't be chosen in the future.
      while (!maxQ.empty() && dp[maxQ.back()] <= dp[i])
        maxQ.pop_back();
      maxQ.push_back(i);
    }

    return dp.back();
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int maxResult(int[] nums, int k) {
    // Stores dp[i] within the bounds.
    Deque<Integer> maxQ = new ArrayDeque<>(List.of(0));
    // dp[i] := the maximum score to consider nums[0..i]
    int[] dp = new int[nums.length];
    dp[0] = nums[0];

    for (int i = 1; i < nums.length; ++i) {
      // Pop the index if it's out-of-bounds.
      if (maxQ.peekFirst() + k < i)
        maxQ.pollFirst();
      dp[i] = dp[maxQ.peekFirst()] + nums[i];
      // Pop indices that won't be chosen in the future.
      while (!maxQ.isEmpty() && dp[maxQ.peekLast()] <= dp[i])
        maxQ.pollLast();
      maxQ.offerLast(i);
    }

    return dp[nums.length - 1];
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def maxResult(self, nums: list[int], k: int) -> int:
    # Stores dp[i] within the bounds.
    maxQ = collections.deque([0])
    # dp[i] := the maximum score to consider nums[0..i]
    dp = [0] * len(nums)
    dp[0] = nums[0]

    for i in range(1, len(nums)):
      # Pop the index if it's out-of-bounds.
      if maxQ[0] + k < i:
        maxQ.popleft()
      dp[i] = dp[maxQ[0]] + nums[i]
      # Pop indices that won't be chosen in the future.
      while maxQ and dp[maxQ[-1]] <= dp[i]:
        maxQ.pop()
      maxQ.append(i)

    return dp[-1]