LeetCode - Problem 239 - Sliding Window Maximum

Problem Description

Given an array 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.

For example, Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.

Window position                Max
---------------               -----
[1  3  -1] -3  5  3  6  7       3
 1 [3  -1  -3] 5  3  6  7       3
 1  3 [-1  -3  5] 3  6  7       5
 1  3  -1 [-3  5  3] 6  7       5
 1  3  -1  -3 [5  3  6] 7       6
 1  3  -1  -3  5 [3  6  7]      7

Therefore, return the max sliding window as [3,3,5,5,6,7].

Note: You may assume k is always valid, ie: 1 ≤ k ≤ input array’s size for non-empty array.

Follow up: Could you solve it in linear time?

Solution

  • C++
vector<int> maxSlidingWindow(vector<int> & nums, int k) {
        // A container for index in the current window
        deque<int> dq;
        // A container for max values as a result
        vector<int> result;
        // Iterate from begin to end in the array
        for (int i = 0; i<nums.size(); i++) {
            // Erase value in the front as the window move forward
            if (!dq.empty() && dq.front() == i-k) dq.pop_front();
            // Keep only the index of the largest number in the window and 
            // the index of the rightmost number in the window in container dq
            while (!dq.empty() && nums[dq.back()] < nums[i]) dq.pop_back();
            dq.push_back(i);
            // Push the max value to the result vector
            if (i >= k-1) result.push_back(nums[dq.front()]);
        }
        return result;
    }