ProgrammingVery hardTCS CodeVita · Infosys HackWithInfy

What is printed?

What is printed?
from collections import deque
def win_max(a, k):
    dq = deque()
    out = []
    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:
            out.append(a[dq[0]])
    return out
print(win_max([1, 3, -1, -3, 5, 3, 6, 7], 3))
  1. A. [3, 3, 5, 3, 6, 7]
  2. B. [1, 3, 3, 5, 6, 7]
  3. C. [3, 3, 5, 5, 5, 7]
  4. D. [3, 3, 5, 5, 6, 7]

Correct answer: D. [3, 3, 5, 5, 6, 7]

The deque keeps indices whose values decrease from front to back, and its front is the maximum of the current window of size 3. The windows give 3, 3, 5, 5, 6, 7.

More Python Programming questions

Exams that ask this topic