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?- A. 9 9
- B. 5 9
- C. 5 8
- 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
- Problem: A council of two parties, R and D, votes in rounds in seat order. On their turn a member bans the next opposing member who has…
- Problem: People stand in a line facing right with distinct heights. Person i can see person j > i if everyone strictly between them is…
- Problem: An employee's day is 'tiring' if they worked more than 8 hours. Find the longest run of consecutive days in which tiring days…
- Problem: A sorted list of ticket prices is searched with Python's bisect module. python from bisect import bisectleft, bisectright a =…
- Problem: Orders (name, priority) are sorted by priority only, using Python's sorted with a key. python orders = [("ravi", 3), ("asha", 1)…
- Problem: A juice stall sells a ₹5 cup; customers pay with ₹5, ₹10 or ₹20 notes and the stall starts with no change. Decide whether every…