Skip to content

Commit 6a7bd63

Browse files
feature: Adding MinSumKSizeSubarray in Sliding
Window Algorithm
1 parent 7cf568c commit 6a7bd63

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package com.thealgorithms.slidingwindow;
2+
3+
/**
4+
* The Sliding Window algorithm is used to find the minimum sum of a subarray
5+
* of a fixed size k within a given array.
6+
*
7+
* <p>
8+
* Worst-case performance O(n)
9+
* Best-case performance O(n)
10+
* Average performance O(n)
11+
* Worst-case space complexity O(1)
12+
*
13+
* This class provides a static method to find the minimum sum of a subarray
14+
* with a specified length k.
15+
*
16+
* @author Rashi Dashore (https://github.com/rashi07dashore)
17+
*/
18+
public final class MinSumKSizeSubarray {
19+
20+
// Prevent instantiation
21+
private MinSumKSizeSubarray() {}
22+
23+
/**
24+
* This method finds the minimum sum of a subarray of a given size k.
25+
*
26+
* @param arr is the input array where the minimum sum needs to be found
27+
* @param k is the size of the subarray
28+
* @return the minimum sum of the subarray of size k
29+
*/
30+
31+
public static int minSumKSizeSubarray(int[] arr, int k) {
32+
if (arr.length < k) {
33+
return -1; // Edge case: not enough elements
34+
}
35+
36+
int minSum;
37+
int windowSum = 0;
38+
39+
// Calculate the sum of the first window
40+
for (int i = 0; i < k; i++) {
41+
windowSum += arr[i];
42+
}
43+
minSum = windowSum;
44+
45+
// Slide the window across the array
46+
for (int i = k; i < arr.length; i++) {
47+
windowSum += arr[i] - arr[i - k];
48+
minSum = Math.min(minSum, windowSum);
49+
}
50+
return minSum;
51+
}
52+
}

0 commit comments

Comments
 (0)