Python – Sliding Window Maximum: Brute‑Force vs Deque (DSA)

Publié le: 09 mai 2025
sur la chaîne: CodeVisium
508
3

Finding the maximum for every contiguous subarray (“window”) of size k in an array is a classic sliding‑window challenge.

Brute‑Force Approach:

For each window start index, scan the next k elements to compute the maximum via Python’s built‑in max().

Time: O(n·k) , where n is the length of nums.

Use When: k is very small or input size is modest.

Deque (Monotonic Queue) Approach:

Maintain a double‑ended queue of indices whose corresponding values are in decreasing order.

For each new element, pop indices out of range, then pop smaller values from the back to keep the deque “monotonic.”

The front of the deque always holds the index of the current window’s maximum.

Time: O(n), since each element is added and removed at most once.

Space: O(k) for the deque.

Use When: k and n are large; optimal for performance‑critical applications.

Codes:

🔄 Approach 1: Brute‑Force (O(n·k) time, O(1) extra space)
def maxSlidingWindow_bruteforce(nums, k):
n = len(nums)
if n * k == 0:
return []
result = []
for i in range(n - k + 1):
scan the next k elements to find the max
result.append(max(nums[i:i + k]))
return result

⚡ Approach 2: Deque (Monotonic Queue) – O(n) time, O(k) space
from collections import deque

def maxSlidingWindow_deque(nums, k):
n = len(nums)
if n * k == 0:
return []
deq = deque() # will store indices, elements in decreasing order
result = []

for i, v in enumerate(nums):
remove indices that are out of this window
while deq and deq[0] v i - k + 1:
deq.popleft()
remove smaller values from the right
while deq and nums[deq[-1]] v v:
deq.pop()
deq.append(i)
append the current max to result
if i v= k - 1:
result.append(nums[deq[0]])
return result


Sur cette page du site, vous pouvez voir la vidéo en ligne Python – Sliding Window Maximum: Brute‑Force vs Deque (DSA) durée heure minute seconde en bonne qualité , qui a été Téléchargé par l'utilisateur CodeVisium 09 mai 2025, Partagez le lien avec vos amis et connaissances, sur youtube cette vidéo a déjà été regardée 508 fois et il a aimé 3 téléspectateurs. Bon visionnage!