Given an array of positive integers nums
and a positive integer target
, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr]
of which the sum is greater than or equal to target
. If there is no such subarray, return 0
instead.
Input: target = 7, nums = [2,3,1,2,4,3] Output: 2
Explanation: The subarray [4,3] has the minimal length under the problem constraint.
public class MinimumSubarrayOfSumk {
public static void main(String[] args) {
int[] arr = {
10,5,13,4,8,4,5,11,14,9,16,10,20,8};
int target =80;
int i =-1;
int j=-1;
int sum = 0;
int length = Integer.MAX_VALUE;
while (true){
boolean f1 = false,f2 = false;
while (i<arr.length-1 && sum<target){
f1 = true;
i++;
sum+=arr[i];
if(sum>=target){
length = Math.min(length,i-j);
break;
}
// f1 = true;
}
while (j<i && sum>=target){
f2 = true;
j++;
sum-=arr[j];
if(sum>=target){
length = Math.min(length,i-j);
}else{
break;
}
// f2 = true;
}
if(!f1 && !f2){
break;
}
}
System.out.println(length);
}
}
No comments:
Post a Comment