Code Logo

Minimum Sum of K Consecutive

Published at24 Jul 2026
Easy 3 views
Like0

Given an array of integers and a window size k, find the minimum sum among all subarrays of length k. Return the minimum sum.

For example, in [1, 3, -2, 4, -5] with k=3, windows: [1,3,-2] sum=2, [3,-2,4] sum=5, [-2,4,-5] sum=-3. Minimum sum is -3. With k=2: [1,3]=4, [3,-2]=1, [-2,4]=2, [4,-5]=-1. Minimum is -1.

Finding the minimum subarray sum of fixed length is a fundamental sliding window problem. It is used in time series analysis, financial data processing, and signal smoothing.

The solution computes the sum of the first k elements, then slides the window: subtract outgoing, add incoming, and track the minimum sum.

Edge cases include k larger than the array (return 0), an empty array (return 0), and all positive or all negative values (the minimum is found correctly).

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

Solution Approach

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

function minSumK(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]
  minSum = sum
  for i = k to length(arr) - 1
    sum = sum - arr[i - k] + arr[i]
    if sum < minSum then minSum = sum
  return minSum

Sum the first window. Slide, update the sum, and track the minimum. Return the minimum sum found across all windows.

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