Maximize count of non | Java 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
import java . util . * ; class GFG { static int CtSubarr ( int [ ] arr , int N , int K ) { Set < Integer > st = new HashSet < Integer > ( ) ; int prefixSum = 0 ; st . add ( prefixSum ) ; int res = 0 ; for ( int i = 0 ; i < N ; i ++ ) { prefixSum += arr [ i ] ; if ( st . contains ( prefixSum - K ) ) { res += 1 ; prefixSum = 0 ; st . clear ( ) ; st . add ( 0 ) ; } st . add ( prefixSum ) ; } return res ; } public static void main ( String [ ] args ) { int arr [ ] = { - 2 , 6 , 6 , 3 , 5 , 4 , 1 , 2 , 8 } ; int N = arr . length ; int K = 10 ; System . out . println ( CtSubarr ( arr , N , K ) ) ; } }