Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

sliding window max

vector<int> solve(vector<int>& nums, int k) {
    vector<int>ans;
    if(k>nums.size())return ans;
    deque<int>dq;
    for(int i = 0; i < k; i++)
    {
        while(!dq.empty() && nums[dq.back()]<=nums[i])
        {
            dq.pop_back();
        }
        dq.push_back(i);
    }
    ans.push_back(nums[dq.front()]);
    for(int i = k; i < nums.size(); i++)
    {
        if(!dq.empty() && dq.front()<=i-k)dq.pop_front();
        while(!dq.empty() && nums[dq.back()]<=nums[i])
        {
            dq.pop_back();
        }
        dq.push_back(i);
        ans.push_back(nums[dq.front()]);
    }
    return ans;
}
 
PREVIOUS NEXT
Tagged: #sliding #window #max
ADD COMMENT
Topic
Name
8+5 =