0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Leetcode] Sliding Window Maximum

Posted at

Use deque to keep a decrease queue. Total run-time of O(n).

class Solution {
public:
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        typedef pair<int, int> pii;
        deque<pii> dq;
        int n = nums.size();
        vector<int> ans;
        for(int i = 0; i < n; i++) {
            while(!dq.empty() && dq.back().first < nums[i]) dq.pop_back();
            dq.push_back(make_pair(nums[i], i));
            while(dq.front().second <= i - k) dq.pop_front();
            if (i >= k - 1) ans.push_back(dq.front().first);
        }
        return ans;
    }
};

Reference:
Sliding Window Minimum Implementations
Double ended queue

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?