Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Start at index 0 and finish at the last index; from i you may jump to any of i+1..i+k. Maximise the sum of visited values (monotonic deque of dp values).

Problem: Start at index 0 and finish at the last index; from i you may jump to any of i+1..i+k. Maximise the sum of visited values (monotonic deque of dp values).
from collections import deque
def best(a, k):
    dp = [0] * len(a); dp[0] = a[0]; dq = deque([0])
    for i in range(1, len(a)):
        while dq[0] < i - k: dq.popleft()
        dp[i] = a[i] + dp[dq[0]]
        while dq and dp[dq[-1]] <= dp[i]: dq.pop()
        dq.append(i)
    return dp[-1]
print(best([1, -5, -2, 4, -7, -1, 3, -6, 2], 2))
What is printed?
  1. A. 5
  2. B. 4
  3. C. 8
  4. D. 7

Correct answer: D. 7

dp[i] = a[i] + max(dp[i−k..i−1]); the deque keeps the window maximum in O(1). The best route is 1 → −2 → 4 → −1 → 3 → 2 = 7: with k = 2 you must land on one of every two consecutive cells, so −2 (not −5) and −1 (not −7) are paid while −6 is jumped over. Exhaustive search agrees.

More Coding Interview Problems questions

Exams that ask this topic