Longest subarray having sum K | Set 2 | To store the prefix sum array ; Function for searching the lower bound of the subarray ; Iterate until low less than equal to high ; For each mid finding sum of sub array less than or equal to k ; Return the final answer ; Function to find the length of subarray with sum K ; Initialize sum to 0 ; Push the prefix sum of the array arr [ ] in prefix [ ] ; Search r for each i ; Update ans ; Print the length of subarray found in the array ; Given array arr [ ] ; Given sum K ; Function Call
let v = [ ] ; function bin ( val , k , n ) { let lo = 0 ; let hi = n ; let mid ; let ans = - 1 ; while ( lo <= hi ) { mid = lo + parseInt ( ( hi - lo ) / 2 ) ; if ( v [ mid ] - val <= k ) { lo = mid + 1 ; ans = mid ; } else hi = mid - 1 ; } return ans ; } function findSubarraySumK ( arr , N , K ) { let sum = 0 ; v . push ( 0 ) ; for ( let i = 0 ; i < N ; i ++ ) { sum += arr [ i ] ; v . push ( sum ) ; } let l = 0 , ans = 0 , r ; for ( let i = 0 ; i < N ; i ++ ) { r = bin ( v [ i ] , K , N ) ; ans = Math . max ( ans , r - i ) ; } document . write ( ans ) ; } let arr = [ 6 , 8 , 14 , 9 , 4 , 11 , 10 ] ; let N = arr . length ; let K = 13 ; findSubarraySumK ( arr , N , K ) ;