Maximum Sum of K Consecutive
Given an array of integers and a window size k, find the maximum sum among all subarrays of length k. Return the maximum sum.
For example, in [1, 4, 2, 10, 3] with k=3, windows: [1,4,2] sum=7, [4,2,10] sum=16, [2,10,3] sum=15. Maximum is 16. With k=2: [1,4]=5, [4,2]=6, [2,10]=12, [10,3]=13. Maximum is 13.
Maximum sum subarray of fixed length is the classic sliding window problem. It is the foundation for more complex sliding window problems involving averages, products, and other aggregates.
The solution computes the sum of the first k elements, then slides: subtract outgoing, add incoming, and track the maximum sum.
Edge cases include k larger than the array (return 0), an empty array (return 0), and all negative values (the maximum is the least negative sum).
Example Input & Output
Algorithm Flow

Solution Approach
Use a sliding window to maintain the sum incrementally and track the maximum.
Sum the first window. Slide and update the sum. Track the maximum sum encountered. Return the maximum.
Time complexity is O(n), space complexity is O(1).
Best Answers
class Solution {
public int solution(int[] nums, int k) {
if (nums.length==0) return 0;
int w=0;for(int i=0;i<k;i++)w+=nums[i];
int b=w;
for(int i=k;i<nums.length;i++){w+=nums[i]-nums[i-k];b=Math.max(b,w);}
return b;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
