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 ; Pick a starting point ; 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
function subArraySum ( arr , n , sum ) { let curr_sum = arr [ 0 ] , start = 0 , i ; for ( i = 1 ; i <= n ; i ++ ) { while ( curr_sum > sum && start < i - 1 ) { curr_sum = curr_sum - arr [ start ] ; start ++ ; } if ( curr_sum == sum ) { let p = i - 1 ; document . write ( " " + start + " " + p + " " ) ; return 1 ; } if ( i < n ) curr_sum = curr_sum + arr [ i ] ; } document . write ( " " ) ; return 0 ; } let arr = [ 15 , 2 , 4 , 8 , 9 , 5 , 10 , 23 ] ; let n = arr . length ; let sum = 23 ; subArraySum ( arr , n , sum ) ;