Tutorialspoint
Problem
Solution
Submissions

Sliding Window Maximum

Certification: Advanced Level Accuracy: 0% Submissions: 0 Points: 15

Write a C program to find the maximum element in every sliding window of size k in an array. Given an array of integers and a window size k, slide the window from left to right and return an array containing the maximum element in each window position.

Example 1
  • Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
  • Output: [3,3,5,5,6,7]
  • Explanation:
    • Window [1,3,-1] -> maximum is 3.
    • Window [3,-1,-3] -> maximum is 3.
    • Window [-1,-3,5] -> maximum is 5.
    • Continue sliding and finding maximum in each window.
Example 2
  • Input: nums = [1], k = 1
  • Output: [1]
  • Explanation:
    • Only one element in array and window size is 1.
    • The maximum (and only) element in the window is 1.
    • Result array contains single element [1].
Constraints
  • 1 <= nums.length <= 10^5
  • -10^4 <= nums[i] <= 10^4
  • 1 <= k <= nums.length
  • Time Complexity: O(n) using deque approach
  • Space Complexity: O(k) for storing indices in deque
ArraysDequeAdobeTutorix
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use a deque (implemented with array) to store indices of array elements
  • The deque will store indices in decreasing order of their corresponding values
  • The front of deque always contains the index of maximum element in current window
  • Remove indices that are out of current window from front of deque
  • Remove indices from rear of deque if their values are smaller than current element
  • Add current element's index to rear of deque and store front element as maximum

Steps to solve by this approach:

 Step 1: Initialize a deque to store indices of array elements in decreasing order of their values
 Step 2: Process the first window by adding indices while maintaining decreasing order in deque
 Step 3: The front of deque contains the index of maximum element in current window
 Step 4: For each subsequent element, remove indices that are outside current window from front
 Step 5: Remove indices from rear whose corresponding values are smaller than current element
 Step 6: Add current element's index to rear and record the maximum (front element) in result
 Step 7: Continue until all windows are processed, maintaining O(n) time complexity

Submitted Code :