Minimum Sum of K Consecutive
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
Algorithm Flow
Solution Approach
Use a sliding window to maintain the sum incrementally and track the minimum.
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
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;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
