Count maximum non | C # program for the above approach ; Function to count maximum number of non - overlapping subarrays with sum equals to the target ; Stores the readonly 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
using System ; using System . Collections . Generic ; class GFG { static int maximumSubarrays ( int [ ] arr , int N , int target ) { int ans = 0 ; int availIdx = - 1 ; int cur_sum = 0 ; Dictionary < int , int > mp = new Dictionary < int , int > ( ) ; mp . Add ( 0 , 1 ) ; for ( int i = 0 ; i < N ; i ++ ) { cur_sum += arr [ i ] ; if ( mp . ContainsKey ( cur_sum - target ) && mp [ cur_sum - target ] >= availIdx ) { ans ++ ; availIdx = i ; } if ( mp . ContainsKey ( cur_sum ) ) mp [ cur_sum ] = i ; else mp . Add ( cur_sum , i ) ; } return ans ; } public static void Main ( String [ ] args ) { int [ ] arr = { 2 , - 1 , 4 , 3 , 6 , 4 , 5 , 1 } ; int N = arr . Length ; int target = 6 ; Console . Write ( maximumSubarrays ( arr , N , target ) ) ; } }