1696. Jump Game VI
Problem
Tags: Array
, Dynamic Programming
, Queue
, Sliding Window
, Heap (Priority Queue)
, Monotonic Queue
You are given a 0-indexed integer array nums
and an integer k
.
You are initially standing at index 0
. In one move, you can jump at most k
steps forward without going outside the boundaries of the array. That is, you can jump from index i
to any index in the range [i + 1, min(n - 1, i + k)]
inclusive.
You want to reach the last index of the array (index n - 1
). Your score is the sum of all nums[j]
for each index j
you visited in the array.
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 your jumps forming the subsequence [1,-1,4,3] (underlined above). The sum is 7.
Example 2:
Input: nums = [10,-5,-2,4,0,3], k = 3
Output: 17
Explanation: You can choose your jumps forming the subsequence [10,4,3] (underlined above). 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
Code
JS
// 1696. Jump Game VI (1/22/53408)
// Runtime: 144 ms (68.42%) Memory: 52.20 MB (86.84%)
/**
* @param {number[]} nums
* @param {number} k
* @return {number}
*/
var maxResult = function(nums, k) {
const n = nums.length;
// dp 陣列用來存到 i 處最大分數
let dp = new Array(n);
// queue 用來存候選位置
let queue = [];
// 初始化,分別放入 i = 0 的值與位置
dp[0] = nums[0];
queue.push(0);
// 遍歷 nums
for (let i = 1; i < n; i++) {
// 把 queue 中超過可到達範圍的位置移除
while (queue.length && queue[0] < i - k) queue.shift();
// i 位置的最大分數會是 queue 中離 i 最遠的最大分數加上 i 位置的分數
dp[i] = dp[queue[0]] + nums[i];
// 把 queue 中位置的最大分數比 i 位置的最大分數小的位置移除
while (queue.length && dp[i] >= dp[queue[queue.length - 1]]) queue.pop();
// 把 i 位置放入 queue
queue.push(i);
}
// 回傳到最後一個位置的最大分數
return dp[n - 1];
};