Accepted but need help


  • 0
    B

    If you un-commented the for loop lines and commented out the current limit, the output ("result") is empty. Can anyone throw some light?

    vector<int> maxSlidingWindow(vector<int>& nums, int k)
    {
        list<pair<int, int> > deque;
        vector<int> result;
        int limit = nums.size() - k;
        for (int i = -k + 1; i <= limit; ++i) 
                          // i <= (nums.size() - k); ++i)
        {   
            // Kill all values smaller than incoming
            while (!deque.empty() && nums[i + k - 1] > deque.back().second) deque.pop_back();
    
            // Allow smaller incoming values or larger ones after the kill.
            deque.push_back(make_pair(i, nums[i + k - 1]));
    
            // Expire values in the front of the queue.
            while (i - deque.front().first >= k) deque.pop_front();
    
            // Ignore when not at least k elements.
            if (i >= 0) result.push_back(deque.front().second);
        }   
        return result;
    }
    
    int main()
    {
        int k = 3;
        vector<int> nums = {1,3,-1,-3,5,3,6,7};
        vector<int> max = maxSlidingWindow(nums, k);
    
        for (auto x : max) cout << x << ",";
        cout << endl;
    
        return 0;
    }
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.