⌘K
Flycodx

Sliding Window Maximum

Sliding Window Maximum

HardArrays80% accepted

Given an integer array nums and a window size k, return the maximum element in each sliding window of size k as the window moves from left to right. For an array of size n, there are n-k+1 windows. Your solve(...) function receives these inputs directly as ready-made arguments — no input reading or parsing needed. Just compute and return the answer. Example: n=8, k=3, nums=[1 3 -1 -3 5 3 6 7] → "3 3 5 5 6 7"

Input format — only if your code reads from stdin

Input format (stdin): - First line: two integers n (array size) and k (window size) - Second line: n space-separated integers Output: the maximums for each window position, space-separated on a single line.

Approach

Monotonic deque: maintain a deque of indices where values are decreasing. For each new element, pop from the back any index whose value is ≤ current (they can never be the max). Pop from the front any index that has left the window. The front is always the current window's maximum.

Input

8 3 1 3 -1 -3 5 3 6 7

Output

3 3 5 5 6 7
  • •1 ≤ k ≤ n ≤ 10^5, -10^4 ≤ nums[i] ≤ 10^4
solution.py
Loading editor...
Test 1
Test 2
Test 3

Press Run to test your custom input, or Submit to judge against all test cases.

Sign in to continue

Create a free account to run code, submit solutions and track progress.

  • Free forever — no credit card
  • 10+ languages with live execution
  • Points, streaks & leaderboards
Auto Save OnLn 1, Col 1Spaces: 4UTF-8LFPython 3