Find subarray with given sum | Set 1 ( Nonnegative Numbers ) | Returns true if the there is a subarray of arr [ ] with sum equal to ' sum ' otherwise returns false . Also , prints the result ; Initialize curr_sum as value of first element and starting point as 0 ; Add elements one by one to curr_sum and if the curr_sum exceeds the sum , then remove starting element ; If curr_sum exceeds the sum , then remove the starting elements ; If curr_sum becomes equal to sum , then return true ; Add this element to curr_sum ; If we reach here , then no subarray ; Driver Code
< ? php function subArraySum ( $ arr , $ n , $ sum ) { $ curr_sum = $ arr [ 0 ] ; $ start = 0 ; $ i ; for ( $ i = 1 ; $ i <= $ n ; $ i ++ ) { while ( $ curr_sum > $ sum and $ start < $ i - 1 ) { $ curr_sum = $ curr_sum - $ arr [ $ start ] ; $ start ++ ; } if ( $ curr_sum == $ sum ) { echo " Sum ▁ found ▁ between ▁ indexes " , " ▁ " , $ start , " ▁ " , " and ▁ " , " ▁ " , $ i - 1 ; return 1 ; } if ( $ i < $ n ) $ curr_sum = $ curr_sum + $ arr [ $ i ] ; } echo " No ▁ subarray ▁ found " ; return 0 ; } $ arr = array ( 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 ) ; $ n = count ( $ arr ) ; $ sum = 23 ; subArraySum ( $ arr , $ n , $ sum ) ;