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 ; Driver Code ; Given array arr [ ] ; Given sum target ; Function call
def maximumSubarrays ( arr , N , target ) : NEW_LINE INDENT ans = 0 NEW_LINE availIdx = - 1 NEW_LINE cur_sum = 0 NEW_LINE mp = { } NEW_LINE mp [ 0 ] = - 1 NEW_LINE for i in range ( N ) : NEW_LINE INDENT cur_sum += arr [ i ] NEW_LINE if ( ( cur_sum - target ) in mp and mp [ cur_sum - target ] >= availIdx ) : NEW_LINE INDENT ans += 1 NEW_LINE availIdx = i NEW_LINE DEDENT mp [ cur_sum ] = i NEW_LINE DEDENT return ans NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT arr = [ 2 , - 1 , 4 , 3 , 6 , 4 , 5 , 1 ] NEW_LINE N = len ( arr ) NEW_LINE target = 6 NEW_LINE print ( maximumSubarrays ( arr , N , target ) ) NEW_LINE DEDENT