In: Computer Science
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 1
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].
Example 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].
Example 3
Input: [3, 4, 1, 1, 6], S=8 Output: 3 Explanation: Smallest subarrays with a sum greater than or equal to '8' are [3, 4, 1] or [1, 1, 6].
CODE::
class Main {
public static int findSmallestSubarray(int[] arr, int S){
// write your code here
}
public static void main(String[] args) {
// write your code here
}
}
class Main
{
public static int findSmallestSubarray(int[] arr,int S){
int s=0;
int len=arr.length+1;
for(int i=0;i<arr.length;i++){
s=arr[i];//checking each element if it is greater or equal to S
return 1
if(s>=S)
return 1;
for(int j=i+1;j<arr.length;j++){
s+=arr[j];//add each element to s and check the condition
if(s>=S && (j-i+1)<len){
len=j-i+1;//if sum is greater or equal to S, update len
}
}
}
if(len>arr.length)
return 0;
return len;
}
public static void main(String[] args) {
int arr[]={2,1,5,2,3,2};
System.out.println(findSmallestSubarray(arr,7));//create arrays and
call functions
int arr2[]={2,1,5,2,8};
System.out.println(findSmallestSubarray(arr2,8));
int arr3[]={3,4,1,1,6};
System.out.println(findSmallestSubarray(arr3,8));
}
}
Screenshots:
The output is attached below for reference.
Please follow it.