Maximize count of non | C ++ Program to implement the above approach ; Function to count the maximum number of subarrays with sum K ; Stores all the distinct prefixSums obtained ; Stores the prefix sum of the current subarray ; Stores the count of subarrays with sum K ; If a subarray with sum K is already found ; Increase count ; Reset prefix sum ; Clear the set ; Insert the prefix sum ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int CtSubarr ( int arr [ ] , int N , int K ) { unordered_set < int > st ; int prefixSum = 0 ; st . insert ( prefixSum ) ; int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { prefixSum += arr [ i ] ; if ( st . count ( prefixSum - K ) ) { res += 1 ; prefixSum = 0 ; st . clear ( ) ; st . insert ( 0 ) ; } st . insert ( prefixSum ) ; } return res ; } int main ( ) { int arr [ ] = { -2 , 6 , 6 , 3 , 5 , 4 , 1 , 2 , 8 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; int K = 10 ; cout << CtSubarr ( arr , N , K ) ; }