Polski

Sliding window maximum

For every window of k consecutive measurements report the largest value – in linear time, regardless of k. A monotonic queue on a double-ended queue (deque).

hard · typescript · javascript · python · csharp · java · go · 40 XP

A monitoring dashboard shows, for every second, the peak latency of the last k seconds. There are hundreds of thousands of measurements and the window can hold tens of thousands of them – recomputing the maximum from scratch for every window (O(n · k)) is too slow.

Task

For an array nums and a window size k, return the maxima of consecutive windows nums[i..i+k-1] for i = 0 … n-k (the result has n - k + 1 elements). The input must not be modified.

Signatures: maxSlidingWindow(nums, k) (JS/TS), max_sliding_window(nums, k) (Python), Solution.MaxSlidingWindow (C#), Solution.maxSlidingWindow (Java), MaxSlidingWindow (Go).

Examples

numskResult
[1, 3, -1, -3, 5, 3, 6, 7]3[3, 3, 5, 5, 6, 7]
[4, 4, 4, 2, 4]2[4, 4, 4, 4]
[9, 8, 7, 6, 5]2[9, 8, 7, 6]
[5, 1, 2]3[5]

Constraints

  • 1 ≤ k ≤ n ≤ 200,000, values in the 32-bit int range.

Expected complexity

O(n) time, O(k) extra memory.