← Home

239. Sliding Window Maximum

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
sliding windowC++Markdown
239

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 239. Sliding Window Maximum, the solution in this repository is mainly a sliding window solution.

Guide

What?

The code is easier to read if we treat it as a controlled search through possible states. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: sliding window.

Guide

When?

Reach for this shape when a direct simulation would work logically but waste time revisiting the same information. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are maxSlidingWindow.

Guide

Why?

The win comes from making each line carry responsibility: store the useful state, discard the rest, keep moving.

  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 56 ms, faster than 79.54% of C++ online submissions for Sliding Window Maximum.
02//Memory Usage: 10.7 MB, less than 100.00% of C++ online submissions for Sliding Window Maximum.
03class Solution {
04public:
05    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
06        int curMax = INT_MAX, curMaxPos = -1;
07        vector<int> ans;
08        for(int i = 0; i+k-1 < nums.size(); i++){
09            //[i, i+k-1] : sliding window's range
10            if(nums[i+k-1] >= curMax){
11                /*
12                set curMax's initial value as INT_MAX, 
13                so that in first iteration it will go to 
14                the "else if(i > curMaxPos)" part
15                */
16                curMax = nums[i+k-1];
17                curMaxPos = i+k-1;
18            }else if(i > curMaxPos){
19                /*
20                set curMaxPos's intial value as -1,
21                so that in first iteration it will come here
22                */
23                auto it = max_element(nums.begin()+i, nums.begin()+i+k);
24                curMax = *it;
25                curMaxPos = it - nums.begin();
26            }
27            ans.push_back(curMax);
28        }
29        
30        return ans;
31    }
32};
33
34//deque
35//Runtime: 36 ms, faster than 99.52% of C++ online submissions for Sliding Window Maximum.
36//Memory Usage: 16.7 MB, less than 21.31% of C++ online submissions for Sliding Window Maximum.
37class Solution {
38public:
39    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
40        vector<int> ans;
41        deque<pair<int, int>> window; //decreasing
42        
43        //prepare window: [0, k-2]
44        //used when calculate first element of ans
45        for(int i = 0; i < k-1; i++){
46            while(window.size() > 0 && window.back().first < nums[i]){
47                window.pop_back();
48            }
49            window.push_back(make_pair(nums[i], i));
50        }
51        
52        for(int i = k-1; i < nums.size(); i++){
53            //window range: i-k+1, ... , i
54            
55            //keep it decreasing
56            while((window.size() > 0) && (nums[i] > window.back().first)){
57                window.pop_back();
58            }
59            window.push_back(make_pair(nums[i], i));
60            
61            //discard the element outside window range
62            if(window.front().second == i-k){
63                window.pop_front();
64            }
65            
66            ans.push_back(window.front().first);
67        }
68        
69        return ans;
70    }
71};
72
73//deque, clean
74//https://leetcode.com/problems/sliding-window-maximum/discuss/65884/Java-O(n)-solution-using-deque-with-explanation
75//Runtime: 36 ms, faster than 99.52% of C++ online submissions for Sliding Window Maximum.
76//Memory Usage: 16.4 MB, less than 21.31% of C++ online submissions for Sliding Window Maximum.
77class Solution {
78public:
79    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
80        int n = nums.size();
81        vector<int> ans(n-k+1);
82        /*
83        pair<int, int>: the element in sliding window, its index
84        
85        the headmost element in deque is the index of largest 
86        element in sliding window
87        */
88        deque<pair<int, int>> window; //decreasing
89        
90        for(int i = 0; i < nums.size(); i++){
91            //window range: i-k+1, ... , i
92            
93            //keep it decreasing
94            /*
95            because current element nums[i] is larger than the smallest 
96            element in sliding window and have larger index
97            (which means it will be popped from window later) , 
98            so now window.back() becomes useless
99            */
100            while((window.size() > 0) && (nums[i] > window.back().first)){
101                window.pop_back();
102            }
103            /*
104            although current element may not be the largest in the window,
105            it may be useful when larger elements in the window are popped
106            */
107            window.push_back(make_pair(nums[i], i));
108            
109            //discard the element outside window range
110            if(window.front().second == i-k){
111                window.pop_front();
112            }
113            
114            //query
115            //start to construct ans vector when we first see k elements
116            if(i >= k-1) ans[i-(k-1)] = window.front().first;
117        }
118        
119        return ans;
120    }
121};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.