Data Structures & AlgorithmsVery hardProduct company OA

Problem: Pick two NON-overlapping windows of fixed lengths L and M (either order) to maximise the total of their elements. Prefix sums plus a running best of the first window give O(n).

Problem: Pick two NON-overlapping windows of fixed lengths L and M (either order) to maximise the total of their elements. Prefix sums plus a running best of the first window give O(n).
def two_windows(a, L, M):
    p = [0]
    for x in a: p.append(p[-1] + x)
    def best(L, M):
        res = bestL = 0
        for i in range(L + M, len(a) + 1):
            bestL = max(bestL, p[i - M] - p[i - M - L])
            res = max(res, bestL + p[i] - p[i - M])
        return res
    return max(best(L, M), best(M, L))
print(two_windows([1, 7, 2, 8, 3, 3, 9, 1], 2, 3), two_windows([5, 1, 1, 6, 2], 1, 2))
What is printed?
  1. A. 32 13
  2. B. 29 11
  3. C. 27 13
  4. D. 29 13

Correct answer: D. 29 13

For each end i of the right window (length M), pair it with the best L-window ending at or before its start; then swap roles. First array: the 3-window 7, 2, 8 = 17 followed by the 2-window 3, 9 = 12 → 29 (taking the overall best 3-window 3, 3, 9 = 15 forces a worse partner). Second: 5 then 6, 2 → 13. Greedily taking the single best window first fails, and overlapping windows (the 32 trap) are not allowed. O(n).

More Coding Interview Problems questions

Exams that ask this topic