Smallest Subarray with a given sum
Problem Statement
Given an array of positive numbers and a positive number ‘S’, find the length of the smallest contiguous subarray whose sum is greater than or equal to ‘S’. Return 0, if no such subarray exists.
Example
Input: [2, 1, 5, 2, 3, 2], S=7
Output: 2
Explanation: The smallest subarray with a sum great than or equal to '7' is [5, 2].
Input: [2, 1, 5, 2, 8], S=7
Output: 1
Explanation: The smallest subarray with a sum greater than or equal to '7' is [8].
Solution
public static int getminnum(int a[],int num){
if(a==null||a.length==0){
return 0;
}
int sum = 0;
int windowstart = 0;
int min = Integer.MAX_VALUE;
for ( int windowend =0;windowend<a.length;windowend++){
sum+=a[windowend];
while(sum>=num){
min= Math.min(min,windowend- windowstart + 1);
sum -= a[windowstart];
windowstart++;
}
}
return min;
}
时间复杂度 O ( n ) O(n) O(n),空间复杂度 O ( 1 ) O(1) O(1)。