Code Logo

Minimum Sum of K Consecutive

Published at24 Jul 2026
Easy 2 views
Like0

Find the minimum sum of any k consecutive elements in an array.

Use a sliding window of size k. Initialize the window state with the first k elements. Slide the window one position at a time, updating the state efficiently. Track the minimum across all windows.

The sliding window technique processes each element exactly twice (once when it enters, once when it leaves), giving O(n) time complexity with O(1) extra space.

Edge cases include empty arrays (return appropriate default like 0), k larger than array length (return default), and single-element arrays where k=1.

Calculate the sum of each contiguous subarray of length k. Track the minimum sum seen.

Example Input & Output

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

Algorithm Flow

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

Solution Approach

Initialize the sliding window with the first k elements. Compute the initial minimum. For each position i from k to n-1, update the window by removing element i-k and adding element i. Update the result if the new window value is better.

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.min(b,w);}
        return b;
    }
}