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?- A. 5
- B. 4
- C. 8
- 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
- Problem: Move from the top-left to the bottom-right cell of a height grid (4 directions). The effort of a route is the largest absolute…
- Problem: n computers and a list of cables. You may unplug any cable and reconnect it elsewhere. Find the minimum number of moves to…
- Problem: A tree on nodes 1..n received one extra edge. Return the LAST edge in the input whose removal leaves a tree (union-find). python…
- Problem: Replace each word of a sentence by its shortest root from a dictionary (if any root is a prefix). python def replace(roots…
- Problem: Find the shortest palindrome obtainable by adding characters only in FRONT of s, using the KMP failure function of s + '#' +…
- Problem: Is s made of one substring repeated two or more times? Trick: check whether s occurs in (s + s) with the first and last…