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

Veröffentlicht am: 09 Mai 2025
auf dem Kanal: 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


Auf dieser Seite können Sie das Online-Video Python – Sliding Window Maximum: Brute‑Force vs Deque (DSA) mit der Dauer stunde minuten sekunde in guter Qualität ansehen, das der Benutzer CodeVisium 09 Mai 2025 hochgeladen hat, den Link mit Freunden und Bekannten teilen, dieses Video wurde auf Youtube bereits 508 Mal angesehen und es wurde von 3 den Zuschauern gefallen. Viel Spaß beim Betrachtenden Zuschauern gefallen!