Sponsored
Sponsored
This approach employs dynamic programming in combination with a deque to keep track of the best scores possible when jumping to each index within constraints. By using a decreasing deque, we efficiently maintain the maximum score in a window of size k
.
Time Complexity: O(n), because each element is inserted and removed from the deque at most once. Space Complexity: O(k), to store the window of indices in the deque.
1var maxResult = function(nums, k) {
2 const n = nums.length;
3 const deque = [0];
4 for (let i = 1; i < n; i++) {
5 while (deque.length && deque[0] < i - k) {
6 deque.shift();
7 }
8 nums[i] += nums[deque[0]];
9 while (deque.length && nums[i] >= nums[deque[deque.length - 1]]) {
10 deque.pop();
11 }
12 deque.push(i);
13 }
14 return nums[n - 1];
15};
In this JavaScript implementation, we use an array to simulate a deque. We iterate through the nums array, updating each element with the maximum possible score using indices stored in the deque. This approach ensures that at each step, only the maximum score in the allowable jump range is considered.
This approach involves using a dynamic programming solution where we keep track of the best scores using a max-heap (priority queue). By pushing elements onto the heap, we ensure that the maximum score is always accessible, facilitating quick updates for each step in our process.
Time Complexity: O(n log k) due to heap operations. Space Complexity: O(k), maintaining up to k elements in the heap.
1using System.Collections.Generic;
public class Solution {
public int MaxResult(int[] nums, int k) {
var maxHeap = new PriorityQueue<(int, int), int>(Comparer<int>.Create((a, b) => b - a));
maxHeap.Enqueue((nums[0], 0), nums[0]);
for (int i = 1; i < nums.Length; i++) {
while (maxHeap.Peek().Item2 < i - k) {
maxHeap.Dequeue();
}
nums[i] += maxHeap.Peek().Item1;
maxHeap.Enqueue((nums[i], i), nums[i]);
}
return nums[^1];
}
}
Utilizing a priority queue structuring as a max-heap in this C# solution allows for quick access to the maximum score at each stage required when iterating through the nums array.