## Maximum Sum of Subarrays of Size K

###### DESCRIPTION

Given an array of integers nums and an integer k, find the maximum sum of any contiguous subarray of size k.

###### EXAMPLES

**Example 1**:
Input:

`nums = [2, 1, 5, 1, 3, 2] k = 3`

Output:

`9`

Explanation: The subarray with the maximum sum is [5, 1, 3] with a sum of 9.

Run your code to see results here

## Explanation

We maintain a fixed size window of size k throughout the array, and return the maximum sum of all those windows at the end.

## Solution

def max_subarray_sum(nums, k):max_sum = 0state = 0start = 0for end in range(len(nums)):state += nums[end]if end - start + 1 == k:max_sum = max(max_sum, state)state -= nums[start]start += 1return max_sum

start

max subarray sum of size k

0 / 16

1x

Compare UsCompare to Interviewing.io

© 2024 Optick Labs Inc. All rights reserved.

Loading comments...