Lv.3arraydequesliding-window
Sliding Window Maximum
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
Given an integer array nums and a window size k, slide a window of length k from left to right one step at a time and
return the maximum inside the window at each position (nums.length - k + 1 values).
Examples
| nums | k | result |
|---|---|---|
[1, 3, -1, -3, 5, 3, 6, 7] | 3 | [3, 3, 5, 5, 6, 7] |
[4, 2] | 1 | [4, 2] |
[9, 8, 7, 6] | 4 | [9] |
Efficiency
This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.
Function signature
solution(nums: int[], k: int) → int[]
Constraints
-
knums.length -
nums[i]
Expected complexity
- Time
- O(N)
- Space
- O(K)
Examples
| nums | k | Expected |
|---|---|---|
[1,3,-1,-3,5,3,6,7] | 3 | [3,3,5,5,6,7] |
[4,2] | 1 | [4,2] |
[9,8,7,6] | 4 | [9] |
Hint
Hint
Keep a deque of indices whose values are decreasing: pop smaller-or-equal values from the back before pushing, pop the front when it leaves the window, and the front is the window maximum. Each index enters and leaves once, so . Rescanning every window is and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1372 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 3 | inputs and outputs |
| correctness | 40 | 9 | verdict only |
| performance | 60 | 4 | verdict only |