Complete the code to calculate the sum of the first window of size k in the array.
def initial_window_sum(arr, k): window_sum = sum(arr[[1]:k]) return window_sum
The first window starts at index 0, so we sum from index 0 to k-1.
Complete the code to slide the window by one position and update the sum.
def slide_window_sum(arr, window_sum, start, k): window_sum = window_sum - arr[start] + arr[start + [1]] return window_sum
When sliding the window, we remove the element at the start and add the element at start + k.
Fix the error in the code to correctly find the maximum sum of any window of size k.
def max_window_sum(arr, k): max_sum = sum(arr[0:k]) window_sum = max_sum for i in range(1, len(arr) - k + 1): window_sum = window_sum - arr[i - 1] + arr[i + [1]] if window_sum > max_sum: max_sum = window_sum return max_sum
The new element index is i + k - 1 because the window covers k elements starting at i.
Fill both blanks to create a dictionary of window sums keyed by the window's start index.
def window_sums_dict(arr, k): sums = {} current_sum = sum(arr[0:k]) sums[0] = current_sum for i in range(1, len(arr) - k + 1): current_sum = current_sum - arr[i - [1]] + arr[i + [2]] sums[i] = current_sum return sums
Subtract the element leaving at i-1 and add the element entering at i + k - 1.
Fill all three blanks to create a list of averages of each sliding window of size k.
def sliding_window_averages(arr, k): averages = [] window_sum = sum(arr[0:k]) averages.append(window_sum / [1]) for i in range(1, len(arr) - k + 1): window_sum = window_sum - arr[i - [2]] + arr[i + [3]] averages.append(window_sum / k) return averages
The average divides the sum by k. The element leaving is at i-1 and the entering element is at i + k - 1.