1696. Jump Game VI
This page provides solutions for the leetcode problem 1696. Jump Game VI.
Problem Explanation
The problem requires us to calculate maximum score you can get in jump game with following rules.
You are initially standing at index . In one move, you can jump at most steps forward without going outside the boundaries of the array. That is, you can jump from index to any index in the range inclusive.
You want to reach the last index of the array . Your score is the sum of all for each index you visited in the array.
Solution
This problem can be solved using the Deque data Structure. More such problem can be found here.
- Java
class Solution {
public int maxResult(int[] nums, int k) {
int n = nums.length;
int[] score = new int[n];
Deque<Integer> dq = new LinkedList<>();
score[0] = nums[0];
dq.offer(0);
for(int i = 1; i < n; i++) {
while(!dq.isEmpty() && i - dq.peekFirst() > k) dq.pollFirst();
score[i] = score[dq.peekFirst()] + nums[i];
while(!dq.isEmpty() && score[dq.peekLast()] <= score[i]) dq.pollLast();
dq.offer(i);
}
return score[n - 1];
}
}
Complexity
Let's say there are elements in an array.
Time Complexity
Each index is visited only once, so time complexity will be:
Space Complexity
At any given point deque will have elements, so space complexity will be: