This program finds the maximum value in each sliding window of size \( k \) within a given list. It utilizes an efficient algorithm using a deque (double-ended queue) to keep track of potential maximums.
Program Structure
The key to solving this problem efficiently is using a deque which allows us to add and remove elements from both ends in constant time. The algorithm ensures that the deque always contains indices of elements from the array, and these indices are always in decreasing order of their values. This way, the front of the deque always holds the index of the maximum element for the current window.
Python Code
from collections import deque
def max_sliding_window(nums, k):
output = []
deq = deque() # stores indices of the elements
for i in range(len(nums)):
# Remove elements not within the window
if deq and deq[0] < i - k + 1:
deq.popleft()
# Maintain decreasing order in deque
while deq and nums[deq[-1]] < nums[i]: deq.pop() deq.append(i) # Append max for the current window if i >= k - 1:
output.append(nums[deq[0]])
return output
# Example Usage
nums = [1,3,-1,-3,5,3,6,7]
k = 3
print("Maximums of sliding windows:", max_sliding_window(nums, k))
Explanation of the Code
- Function max_sliding_window: Initializes an empty list for output and a deque for indices. It iterates over each element in the list:
- Deque maintenance: Ensures that indices in the deque are within the current window and removes indices of all elements that are less than the current element to maintain the order.
- Result compilation: Starts appending the maximum of each window to the output list once the first window is complete (i.e., when \( i \geq k – 1 \)).
Usage
This function is especially useful for analyzing time-series data where you need to continuously monitor the maximum value in a fixed-size subset. Common applications include financial analysis, meteorological data analysis, and real-time system monitoring.