forked from rituburman/hacktoberfest2020
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsmallestSubArraySum.java
More file actions
21 lines (20 loc) · 900 Bytes
/
smallestSubArraySum.java
File metadata and controls
21 lines (20 loc) · 900 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class MinSizeSubArraySum {
public static int findMinSubArray(int S, int[] arr) {
int windowSum = 0, minLength = Integer.MAX_VALUE;
int windowStart = 0;
for (int windowEnd = 0; windowEnd < arr.length; windowEnd++) {
windowSum += arr[windowEnd]; // add the next element
// shrink the window as small as possible until the 'windowSum' is smaller than 'S'
while (windowSum >= S) {
minLength = Math.min(minLength, windowEnd - windowStart + 1);
windowSum -= arr[windowStart]; // subtract the element going out
windowStart++; // slide the window ahead
}
}
return minLength == Integer.MAX_VALUE ? 0 : minLength;
}
public static void main(String[] args) {
int result = MinSizeSubArraySum.findMinSubArray(7, new int[] { 2, 1, 5, 2, 3, 2 });
System.out.println("Smallest subarray length: " + result);
}
}