Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Split an array into contiguous parts of length at most k; every element of a part becomes that part's maximum. Maximise the final sum.
Problem: Split an array into contiguous parts of length at most k; every element of a part becomes that part's maximum. Maximise the final sum.
def best(a, k):
n = len(a); dp = [0] * (n + 1)
for i in range(1, n + 1):
mx = 0
for L in range(1, min(k, i) + 1):
mx = max(mx, a[i - L]); dp[i] = max(dp[i], dp[i - L] + mx * L)
return dp[n]
print(best([2, 9, 1, 4, 8, 3, 5], 3))What is printed?- A. 49
- B. 52
- C. 63
- D. 56
Correct answer: D. 56
dp[i] tries every last part a[i−L..i−1] (L ≤ k) and adds its max × L. The optimum is [2, 9, 1] → 27, [4, 8, 3] → 24, [5] → 5, total 56; a split such as [2, 9] [1, 4, 8] [3, 5] gives only 18 + 24 + 10 = 52.
More Coding Interview Problems questions
- Problem: Build a binary tree whose leaves (in order) are the array values; each internal node's value is (max leaf on its left) × (max…
- Problem: Longest arithmetic subsequence (not necessarily contiguous) using a dictionary of (difference → length) per index. python def…
- Problem: Count all square submatrices made entirely of 1s. python def count(m): R, C = len(m), len(m[0]); tot = 0 dp = [row[:] for row in…
- Problem: Paint n fence posts with k colours so that no three consecutive posts share a colour. python def ways(n, k): same, diff = 0, k…
- Problem: A pointer starts at index 0 of an array of length n; each step it moves left, right or stays (never leaving the array). Count the…
- Problem: Trade a stock any number of times (one share at most), but after selling you must wait one day before buying again. python def…