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?- A. 32 13
- B. 29 11
- C. 27 13
- 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
- Problem: Remove the SHORTEST contiguous block (not the whole array) so that the remaining sum is divisible by p; return −1 if impossible…
- Problem: Count contiguous subarrays whose MAXIMUM lies in [L, R]: count subarrays with max ≤ R and subtract those with max ≤ L − 1. python…
- Problem: Find the longest substring in which each vowel a, e, i, o, u occurs an even number of times. A 5-bit parity mask of the prefix is…
- Problem: A 3 × 3 matrix has every row and column sorted ascending. Find the k-th smallest value by binary searching on the VALUE and…
- Problem: Each move removes either the leftmost or the rightmost box and subtracts its weight from x. Find the minimum moves to make x…
- Problem: A speech-analysis tool reports the maximum number of vowels in any window of exactly k consecutive letters. python def…