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.
The key idea is to use dynamic programming to keep track of the maximum score to reach each index, and a monotonic queue (deque) to efficiently find the maximum score within the last k steps. This avoids recomputation and ensures optimal substructure.
classSolution {
publicintmaxResult(int[] nums, int k) {
int n = nums.length;
int[] dp =newint[n];
dp[0]= nums[0];
Deque<Integer> dq =new ArrayDeque<>();
dq.offer(0);
for (int i = 1; i < n; i++) {
while (!dq.isEmpty() && dq.peek() < i - k) dq.poll();
dp[i]= nums[i]+ dp[dq.peek()];
while (!dq.isEmpty() && dp[i]>= dp[dq.peekLast()]) dq.pollLast();
dq.offer(i);
}
return dp[n - 1];
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
funmaxResult(nums: IntArray, k: Int): Int {
val n = nums.size
val dp = IntArray(n)
dp[0] = nums[0]
val dq = ArrayDeque<Int>()
dq.add(0)
for (i in1 until n) {
while (dq.isNotEmpty() && dq.first() < i - k) dq.removeFirst()
dp[i] = nums[i] + dp[dq.first()]
while (dq.isNotEmpty() && dp[i] >= dp[dq.last()]) dq.removeLast()
dq.add(i)
}
return dp[n - 1]
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from collections import deque
from typing import List
classSolution:
defmaxResult(self, nums: List[int], k: int) -> int:
n: int = len(nums)
dp: List[int] = [0] * n
dp[0] = nums[0]
dq: deque[int] = deque([0])
for i in range(1, n):
while dq and dq[0] < i - k:
dq.popleft()
dp[i] = nums[i] + dp[dq[0]]
while dq and dp[i] >= dp[dq[-1]]:
dq.pop()
dq.append(i)
return dp[-1]