Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: A traffic monitor reports, for every window of k consecutive minutes, the busiest minute's count, and the dashboard shows the SUM of those window maxima.

Problem: A traffic monitor reports, for every window of k consecutive minutes, the busiest minute's count, and the dashboard shows the SUM of those window maxima.
from collections import deque
def f(a, k):
    dq, s = deque(), 0
    for i, x in enumerate(a):
        while dq and a[dq[-1]] <= x:
            dq.pop()
        dq.append(i)
        if dq[0] <= i - k:
            dq.popleft()
        if i >= k - 1:
            s += a[dq[0]]
    return s
print(f([4, 2, 12, 3, 8, 1, 7], 3))
What is printed?
  1. A. 52
  2. B. 48
  3. C. 44
  4. D. 56

Correct answer: A. 52

The deque keeps indices of a decreasing run, so its front is the window maximum. The five windows have maxima 12, 12, 12, 8, 8, giving 52. 48 comes from wrongly taking 8 for the third window [12, 3, 8].

More Coding Interview Problems questions

Exams that ask this topic