Back to Main
Learn DSA
Depth-First Search
Greedy Algorithms
Get Premium
Sliding Window
Maximum Sum of Subarrays of Size K
easy
DESCRIPTION
Given an array of integers nums and an integer k, find the maximum sum of any contiguous subarray of size k.
Example 1: Input:
Output:
Explanation: The subarray with the maximum sum is [5, 1, 3] with a sum of 9.
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
Login to track your progress
Your account is free and you can post anonymously if you choose.