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
In questa pagina del sito puoi guardare il video online Python – Sliding Window Maximum: Brute‑Force vs Deque (DSA) della durata di ore minuti seconda in buona qualità , che l'utente ha caricato CodeVisium 09 maggio 2025, condividi il link con amici e conoscenti, su youtube questo video è già stato visto 508 volte e gli è piaciuto 3 spettatori. Buona visione!