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) {
    // max queue storing dp[i] within the bounds
    deque<int> dq{0};
    // dp[i] := max 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 (dq.front() + k < i)
        dq.pop_front();
      dp[i] = dp[dq.front()] + nums[i];
      // Pop indices that won't be chosen in the future.
      while (!dq.empty() && dp[dq.back()] <= dp[i])
        dq.pop_back();
      dq.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) {
    // max queue storing dp[i] within the bounds
    Deque<Integer> dq = new ArrayDeque<>(Arrays.asList(0));
    // dp[i] := max 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 (dq.peekFirst() + k < i)
        dq.pollFirst();
      dp[i] = dp[dq.peekFirst()] + nums[i];
      // Pop indices that won't be chosen in the future.
      while (!dq.isEmpty() && dp[dq.peekLast()] <= dp[i])
        dq.pollLast();
      dq.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:
    # max queue storing dp[i] within the bounds
    dq = collections.deque([0])
    # dp[i] := max 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 dq[0] + k < i:
        dq.popleft()
      dp[i] = dp[dq[0]] + nums[i]
      # Pop indices that won't be chosen in the future.
      while dq and dp[dq[-1]] <= dp[i]:
        dq.pop()
      dq.append(i)

    return dp[-1]