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 Code
< ? php function smallestSubWithSum ( $ arr , $ n , $ x ) { $ curr_sum = 0 ; $ min_len = $ n + 1 ; $ 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 ; } $ arr1 = array ( 1 , 4 , 45 , 6 , 10 , 19 ) ; $ x = 51 ; $ n1 = sizeof ( $ arr1 ) ; $ res1 = smallestSubWithSum ( $ arr1 , $ n1 , $ x ) ; if ( $ res1 == $ n1 + 1 ) echo " Not ▁ possible STRNEWLINE " ; else echo $ res1 , " STRNEWLINE " ; $ arr2 = array ( 1 , 10 , 5 , 2 , 7 ) ; $ n2 = sizeof ( $ arr2 ) ; $ x = 9 ; $ res2 = smallestSubWithSum ( $ arr2 , $ n2 , $ x ) ; if ( $ res2 == $ n2 + 1 ) echo " Not ▁ possible STRNEWLINE " ; else echo $ res2 , " STRNEWLINE " ; $ arr3 = array ( 1 , 11 , 100 , 1 , 0 , 200 , 3 , 2 , 1 , 250 ) ; $ n3 = sizeof ( $ arr3 ) ; $ x = 280 ; $ res3 = smallestSubWithSum ( $ arr3 , $ n3 , $ x ) ; if ( $ res3 == $ n3 + 1 ) echo " Not ▁ possible STRNEWLINE " ; else echo $ res3 , " STRNEWLINE " ; ? >