Skip to main content

Best Score With Jumps of at Most K

MediumDynamic programmingQueueSliding window203 tests

You get an integer array nums and an integer k.

You start at index 0 and you must finish at the last index. In one jump you move forward by 1 to k steps. You may not jump past the last index.

Your score is the sum of nums[i] for every index i you land on, including index 0 and the last index. Return the largest score you can get.

If nums has one element, you are already at the end, and the score is nums[0].

Hint

Let best[i] be the largest score for a path that ends at index i. Then best[i] = nums[i] + the largest of best[i - k] to best[i - 1]. Computing that largest value directly costs O(k) per index. A deque of indices whose best values go down from front to back gives it in O(1), so the whole solution is O(n).

Examples

Example 1

Input:
[3,-6,2,-8,-1,5], 2
Output:
9

Land on indices 0, 2, 4 and 5: 3 + 2 + (-1) + 5 = 9. The -6 and -8 are jumped over. You cannot skip both -8 and -1, because that needs a jump of 3.

Example 2

Input:
[-2,-5,-3], 1
Output:
-10

With k = 1 you must land on every index: -2 + (-5) + (-3) = -10.

Example 3

Input:
[4,-7,-7,1], 3
Output:
5

Jump from index 0 straight to index 3: 4 + 1 = 5.

Constraints

  • 1 <= nums.length <= 50
  • 1 <= k <= nums.length
  • -100 <= nums[i] <= 100

Run checks your code against the 3 examples. Submit checks it against all 203 tests and needs a free account. You can also try ideas in the free JavaScript or Python compiler.