You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
classSolution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k){ int n = nums.size(); vector<int> res; res.reserve(n - k + 1);
deque<int> q; // prepare (k - 1) elements for (int i = 0; i < k - 1; ++i) { int value = nums[i]; while (!q.empty() && value > q.back()) { q.pop_back(); } q.push_back(value); }
for (int i = k - 1; i < n; ++i) { // add an element to construct a window whose size is k int value = nums[i]; while (!q.empty() && value > q.back()) { q.pop_back(); } q.push_back(value);
// get the max value in the window // this procedure will repeat (n - k + 1) times int max_value = q.front(); res.push_back(max_value);
// remove the max value if it's the front of the window and // resume with (k - 1) elements in the window for next iteration if (nums[i - (k - 1)] == max_value) { q.pop_front(); } }
q = collections.deque() # prepare (k - 1) elements for i inrange(k-1): value = nums[i] while q and value > q[-1]: q.pop() q.append(value)
res = [] for i inrange(k-1, n): # add an element to construct a window whose size is k value = nums[i] while q and value > q[-1]: q.pop() q.append(value)
# get the max value in the window # this procedure will repeat (n - k + 1) times max_value = q[0] res.append(max_value)
# remove the max value if it's the front of the window and # resume with (k - 1) elements in the window for next iteration if nums[i-(k-1)] == max_value: q.popleft()