Given an array of integers nums and an integer k, find the maximum sum of any contiguous subarray of size k.
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.
Explanation
This problem uses a fixed-size sliding window to efficiently find the maximum sum among all subarrays of length k. Instead of recalculating the sum for each subarray from scratch, we slide the window across the array and update the sum incrementally.
This approach is efficient because we calculate each window’s sum in constant time by:
Adding the new element entering the window (nums[end])
Subtracting the old element leaving the window (nums[start])
Instead of summing k elements for each window (which would be O(n*k)), we do constant work per window, giving us O(n) time complexity.
Solution
def max_subarray_sum(nums, k): max_sum = float('-inf') state = 0 start = 0 for end in range(len(nums)): state += nums[end] if end - start + 1 == k: max_sum = max(max_sum, state) state -= nums[start] start += 1 return max_sum
public class Solution { public int maxSubarraySum(int[] nums, int k) { int maxSum = Integer.MIN_VALUE; int windowSum = 0; int start = 0; for (int end = 0; end < nums.length; end++) { windowSum += nums[end]; if (end - start + 1 == k) { maxSum = Math.max(maxSum, windowSum); windowSum -= nums[start]; start++; } } return maxSum; }}
func maxSubarraySum(nums []int, k int) int { maxSum := -2147483648 windowSum := 0 start := 0 for end := 0; end < len(nums); end++ { windowSum += nums[end] if end-start+1 == k { if windowSum > maxSum { maxSum = windowSum } windowSum -= nums[start] start++ } } return maxSum}
function maxSubarraySum(nums: number[], k: number): number { let maxSum: number = -Infinity; let windowSum: number = 0; let start: number = 0; for (let end = 0; end < nums.length; end++) { windowSum += nums[end]; if (end - start + 1 === k) { maxSum = Math.max(maxSum, windowSum); windowSum -= nums[start]; start++; } } return maxSum;}