Jul 20, 2024
K, find the maximum value in every sliding window of size K in the array.[1, 3, -1, -3, 5, 3, 6, 7] and K=3:
[1, 3, -1] → Maximum = 3[3, -1, -3] → Maximum = 3[-1, -3, 5] → Maximum = 5n-k.function sliding_window_maximum(array, k):
result = []
deque = []
for i in range(len(array)):
# Remove elements not within the window
if deque and deque[0] <= i - k:
deque.pop(0)
# Maintain monotonic decreasing order
while deque and array[deque[-1]] <= array[i]:
deque.pop()
# Insert current element
deque.append(i)
# Append max to result (deque's front element)
if i >= k - 1:
result.append(array[deque[0]])
return result