Maximum of All Subarrays of Size K (Sliding Window Maximum)

beginner
15 min

Maximum of All Subarrays of Size K (Sliding Window Maximum)

Welcome to our comprehensive guide on the Sliding Window Maximum problem, a fundamental concept in the realm of Data Structures and Algorithms! This lesson is designed for beginners and intermediates, so let's dive right in.

Understanding the Problem

The Sliding Window Maximum problem requires finding the maximum element in a given array for every subarray of a specific size. This problem is commonly encountered in data mining, time series analysis, and other real-world applications.

Breaking Down the Problem

Let's break down the problem using a simple example:

nums = [1, 3, -1, -3, 5, 3, 6, 7] k = 3

In this case, we want to find the maximum element in a sliding window of size 3 for each position along the array. The windows and their maximum values would look like this:

  • [1, 3, -1]: Max = 3
  • [3, -1, -3]: Max = 3
  • [-1, -3, 5]: Max = 5
  • [5, 3, 6]: Max = 6
  • [6, 7]: Max = 7

Solving the Problem

To solve the Sliding Window Maximum problem, we'll use a data structure called a deque (double-ended queue), which allows us to efficiently add and remove elements from either end. Here's an example Python code:

python
def max_subarray(nums, k): deque = deque([], maxlen=k) # Initialize the deque max_so_far = float('-inf') # Initialize max_so_far with a small negative number for i, num in enumerate(nums): deque.append(num) # Add the current number to the deque if i >= k - 1: # If we have enough elements in the deque max_so_far = max(max_so_far, max(deque)) # Update max_so_far deque.popleft() # Remove the first element from the deque return max_so_far

šŸ’” Pro Tip: The deque is a double-ended queue that provides fast access to its elements. It's a great choice when dealing with sliding windows.

Putting It All Together

Now that you understand the problem and have a working solution, let's test our function with some examples:

python
print(max_subarray([1, 3, -1, -3, 5, 3, 6, 7], 3)) # Output: 6 print(max_subarray([1, -1, 2, 3, -2, 4], 2)) # Output: 4 print(max_subarray([1, -1, -2, 0, 1], 3)) # Output: 1

šŸ“ Note: The sliding window moves one step at a time, and we update the max_so_far variable at each step.

Quiz Time

Quick Quiz
Question 1 of 1

What is the purpose of the deque data structure in the Sliding Window Maximum problem?

That's all for this lesson on the Sliding Window Maximum problem! With a solid understanding of this concept, you're one step closer to mastering Data Structures and Algorithms. Happy coding! šŸŽ‰