Skip to content

Instantly share code, notes, and snippets.

@KirillLykov
Created June 20, 2019 14:12
Show Gist options
  • Select an option

  • Save KirillLykov/48e15dc57242fd8fb339cf573d12eb31 to your computer and use it in GitHub Desktop.

Select an option

Save KirillLykov/48e15dc57242fd8fb339cf573d12eb31 to your computer and use it in GitHub Desktop.
Problems solved using Max/Min Queue

Data structure itself. We don't store the data itself - only max.

    class MaxQueue {
        deque< pair<int,size_t> > dq; // first is value, second is how many 
        // time this value is used beside itself
        // for example, for  [7,3,4,5] 5 will be used 2 times, 7 0 times
      public:
        void push(int x) {
            size_t cnt = 0;
            while (!dq.empty() && dq.back().first < x) {
                cnt += dq.back().second + 1;
                dq.pop_back();
            }
            dq.emplace_back(x, cnt);
        }
        
        void pop() {
           if (dq.front().second > 0)
               --dq.front().second;
            else
                dq.pop_front();
        }
        
        int max() {
            return dq.front().first;
        }
    };

Find max in all windows of length k:

    // solution 3. Based on maxqueue
    vector<int> maxSlidingWindow(vector<int>& nums, int k) {
        if (nums.size() == 0 || k == 0) return {};
        MaxQueue mq;
        for (int i = 0; i < k-1; ++i)
            mq.push(nums[i]);
        vector<int> res;
        res.reserve(nums.size() - k + 1);
        for (int i = k-1; i < nums.size(); ++i) {
            mq.push(nums[i]);
            res.push_back( mq.max() );
            mq.pop();
        }
        //res.push_back( mq.max() );
        return res;
    }

See alternative solution

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment