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?
  1. A. 49
  2. B. 52
  3. C. 63
  4. 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

Exams that ask this topic