-
Notifications
You must be signed in to change notification settings - Fork 21.1k
Expand file tree
/
Copy pathSmallestSubarrayWithSum.java
More file actions
47 lines (41 loc) · 1.24 KB
/
SmallestSubarrayWithSum.java
File metadata and controls
47 lines (41 loc) · 1.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.thealgorithms.slidingwindow;
/**
* Finds the length of the smallest contiguous subarray
* whose sum is greater than or equal to a given target.
*
* <p>Example:
* arr = [2, 3, 1, 2, 4, 3], target = 7
* Smallest subarray = [4, 3], length = 2
*
* <p>Time complexity: O(n)
* Space complexity: O(1)
*/
public final class SmallestSubarrayWithSum {
// Prevent instantiation
private SmallestSubarrayWithSum() {
}
/**
* Returns the minimal length of a contiguous subarray of which
* the sum ≥ target. If no such subarray exists, returns 0.
*
* @param arr the input array
* @param target the target sum
* @return the minimal subarray length, or 0 if not found
*/
public static int smallestSubarrayLen(int[] arr, int target) {
if (arr == null || arr.length == 0) {
return 0;
}
int left = 0;
int sum = 0;
int minLen = Integer.MAX_VALUE;
for (int right = 0; right < arr.length; right++) {
sum += arr[right];
while (sum >= target) {
minLen = Math.min(minLen, right - left + 1);
sum -= arr[left++];
}
}
return minLen == Integer.MAX_VALUE ? 0 : minLen;
}
}