Thoughts on leetcode 1696
If we use a normal dp, we will get TLE. Therefore, we use a priority queue to keep track of the biggest value of the previous k elements for the element at index i. As i gets bigger, the element in the priority queue might no longer meet the requirement of being in the range of the previous k elements. If this happens, we will delete them from the priority queue immediately.
Solution for leetcode 1696
public int maxResult(int[] nums, int k) {
PriorityQueue<int[]> pq = new PriorityQueue<>((a,b) -> b[1] - a[1]);
pq.add(new int[]{0,nums[0]});
int n = nums.length;
int[] dp = new int[n];
Arrays.fill(dp, Integer.MIN_VALUE);
dp[0] = nums[0];
for(int i = 1; i < n; i++){
while(!pq.isEmpty() && pq.peek()[0] < Math.max(0, i - k)){
pq.poll();
}
dp[i] = pq.peek()[1] + nums[i];
pq.add(new int[]{i, dp[i]});
}
return dp[n - 1];
}