Code Logo

Maximum Sum of K Consecutive

Published at24 Jul 2026
Easy 0 views
Like0

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

Example 1
Input
[],3
Output
0
Example 2
Input
[-1,-2,-3],2
Output
-3
Example 3
Input
[1,2,3,4,5],3
Output
12
Example 4
Input
[5],1
Output
5
Example 5
Input
[2,3,1],2
Output
5

Algorithm Flow

Recommendation Algorithm Flow for Maximum Sum of K Consecutive
Recommendation Algorithm Flow for Maximum Sum of K Consecutive

Solution Approach

Use a sliding window to maintain the sum incrementally and track the maximum.

function maxSumK(arr, k)
  if k > length(arr) or length(arr) == 0 then return 0
  sum = 0
  for i = 0 to k - 1
    sum = sum + arr[i]
  maxSum = sum
  for i = k to length(arr) - 1
    sum = sum - arr[i - k] + arr[i]
    if sum > maxSum then maxSum = sum
  return maxSum

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

java
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;
    }
}