Skip to main content

Sliding Window Maximum

Question

Given an array of integers nums and an integer k, find the maximum value of each subarray of size k of nums.

Example 1
None

Solution

all//Sliding Window Maximum.py


def sliding_window_max(arr, k):
n = len(arr)

# Initialize the result
max_arr = []

# Consider all windows of size k
for i in range(n - k + 1):
curr_max = 0

# Consider the current window
for j in range(i, i + k):
curr_max = max(curr_max, arr[j])

# Store the maximum value
max_arr.append(curr_max)

return max_arr

# Driver code
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
k = 3

# Function call
max_arr = sliding_window_max(arr, k)

# Print the result
print(max_arr)