Smallest subarray with sum greater than a given value | O ( n ) solution for finding smallest subarray with sum greater than x ; Returns length of smallest subarray with sum greater than x . If there is no subarray with given sum , then returns n + 1 ; Initialize current sum and minimum length ; Initialize starting and ending indexes ; Keep adding array elements while current sum is smaller than or equal to x ; If current sum becomes greater than x . ; Update minimum length if needed ; remove starting elements ; Driver Code
using System ; class GFG { static int smallestSubWithSum ( int [ ] arr , int n , int x ) { int curr_sum = 0 , min_len = n + 1 ; int start = 0 , end = 0 ; while ( end < n ) { while ( curr_sum <= x && end < n ) curr_sum += arr [ end ++ ] ; while ( curr_sum > x && start < n ) { if ( end - start < min_len ) min_len = end - start ; curr_sum -= arr [ start ++ ] ; } } return min_len ; } static public void Main ( ) { int [ ] arr1 = { 1 , 4 , 45 , 6 , 10 , 19 } ; int x = 51 ; int n1 = arr1 . Length ; int res1 = smallestSubWithSum ( arr1 , n1 , x ) ; if ( res1 == n1 + 1 ) Console . WriteLine ( " Not ▁ Possible " ) ; else Console . WriteLine ( res1 ) ; int [ ] arr2 = { 1 , 10 , 5 , 2 , 7 } ; int n2 = arr2 . Length ; x = 9 ; int res2 = smallestSubWithSum ( arr2 , n2 , x ) ; if ( res2 == n2 + 1 ) Console . WriteLine ( " Not ▁ Possible " ) ; else Console . WriteLine ( res2 ) ; int [ ] arr3 = { 1 , 11 , 100 , 1 , 0 , 200 , 3 , 2 , 1 , 250 } ; int n3 = arr3 . Length ; x = 280 ; int res3 = smallestSubWithSum ( arr3 , n3 , x ) ; if ( res3 == n3 + 1 ) Console . WriteLine ( " Not ▁ Possible " ) ; else Console . WriteLine ( res3 ) ; } }