Data Structures & AlgorithmsVery hardProduct Company SDE · Amazon/Microsoft-style OA

Problem: A game board has scores a[0..n−1]; from cell i you may jump forward 1..k cells. Starting at 0 and ending at n − 1, maximise the total score of visited cells. dp[i] = a[i] + max(dp[i−k..i−1]) with a monotonic deque.

Problem: A game board has scores a[0..n−1]; from cell i you may jump forward 1..k cells. Starting at 0 and ending at n − 1, maximise the total score of visited cells. dp[i] = a[i] + max(dp[i−k..i−1]) with a monotonic deque.
from collections import deque
def max_score(a, k):
    n = len(a); dp = [0] * n; dp[0] = a[0]; dq = deque([0])
    for i in range(1, n):
        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(max_score([2, -5, -3, 4, -10, -1, 3], 2), max_score([2, -5, -3, 4, -10, -1, 3], 3))
What is printed?
  1. A. 9 9
  2. B. 5 9
  3. C. 5 8
  4. D. 6 9

Correct answer: B. 5 9

The deque keeps indices of the last k cells with decreasing dp, so its front is the window maximum. k = 2: dp = 2, −3, −1, 3, −7, 2, 5 (path 0 → 2 → 3 → 5 → 6). k = 3: dp = 2, −3, −1, 6, −4, 5, 9 (path 0 → 3 → 6 = 2 + 4 + 3; going through cell 5 would give only 8). O(n) total, versus O(n·k) for the plain DP, which is too slow when n = k = 10⁵.

More Coding Interview Problems questions

Exams that ask this topic