The Sliding Window technique is one of the most powerful array/string patterns! 🪟
💡 Think of it like this: Imagine looking at a city through a window on a moving train. The window shows a portion of the city, and as the train moves, the view shifts. In coding, our "window" is a range of elements in an array, and we slide it along!
💭 Go for it! Apply the approach above in your own code. If you get stuck, use the hint below! 🔥
Two types of sliding windows:
Variable-size window template:
# Fixed-size window: Find max sum of k consecutive elements
def max_sum_k(arr, k):
window_sum = sum(arr[:k]) # First window
max_sum = window_sum
for i in range(k, len(arr)):
window_sum += arr[i] # Add new element (right side)
window_sum -= arr[i - k] # Remove old element (left side)
max_sum = max(max_sum, window_sum)
return max_sum
# Instead of recalculating sum for every window (O(n×k)),
# we just add one and remove one (O(n))!
max_sum_subarray([2, 1, 5, 1, 3, 2], 3)
9