Smallest subarray with sum greater than a given value | 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 program
def smallestSubWithSum ( arr , n , x ) : NEW_LINE INDENT curr_sum = 0 NEW_LINE min_len = n + 1 NEW_LINE start = 0 NEW_LINE end = 0 NEW_LINE while ( end < n ) : NEW_LINE INDENT while ( curr_sum <= x and end < n ) : NEW_LINE INDENT curr_sum += arr [ end ] NEW_LINE end += 1 NEW_LINE DEDENT while ( curr_sum > x and start < n ) : NEW_LINE INDENT if ( end - start < min_len ) : NEW_LINE INDENT min_len = end - start NEW_LINE DEDENT curr_sum -= arr [ start ] NEW_LINE start += 1 NEW_LINE DEDENT DEDENT return min_len NEW_LINE DEDENT arr1 = [ 1 , 4 , 45 , 6 , 10 , 19 ] NEW_LINE x = 51 NEW_LINE n1 = len ( arr1 ) NEW_LINE res1 = smallestSubWithSum ( arr1 , n1 , x ) NEW_LINE print ( " Not ▁ possible " ) if ( res1 == n1 + 1 ) else print ( res1 ) NEW_LINE arr2 = [ 1 , 10 , 5 , 2 , 7 ] NEW_LINE n2 = len ( arr2 ) NEW_LINE x = 9 NEW_LINE res2 = smallestSubWithSum ( arr2 , n2 , x ) NEW_LINE print ( " Not ▁ possible " ) if ( res2 == n2 + 1 ) else print ( res2 ) NEW_LINE arr3 = [ 1 , 11 , 100 , 1 , 0 , 200 , 3 , 2 , 1 , 250 ] NEW_LINE n3 = len ( arr3 ) NEW_LINE x = 280 NEW_LINE res3 = smallestSubWithSum ( arr3 , n3 , x ) NEW_LINE print ( " Not ▁ possible " ) if ( res3 == n3 + 1 ) else print ( res3 ) NEW_LINE