Count maximum non | Function to count maximum number of non - overlapping subarrays with sum equals to the target ; Stores the final count ; Next subarray should start from index >= availIdx ; Tracks the prefix sum ; Map to store the prefix sum for respective indices ; Check if cur_sum - target is present in the array or not ; Update the index of current prefix sum ; Return the count of subarrays ; Given array arr [ ] ; Given sum target ; Function Call
function maximumSubarrays ( arr , N , target ) { var ans = 0 ; var availIdx = - 1 ; var cur_sum = 0 ; var mp = new Map ( ) ; mp . set ( 0 , 1 ) ; for ( var i = 0 ; i < N ; i ++ ) { cur_sum += arr [ i ] ; if ( mp . has ( cur_sum - target ) && mp . get ( cur_sum - target ) >= availIdx ) { ans ++ ; availIdx = i ; } mp . set ( cur_sum , i ) ; } return ans ; } var arr = [ 2 , - 1 , 4 , 3 , 6 , 4 , 5 , 1 ] ; var N = arr . length ; var target = 6 ; document . write ( maximumSubarrays ( arr , N , target ) ) ;