Largest subarray with frequency of all elements same | Java program for the above approach ; Function to find maximum subarray size ; Generating all subarray i -> starting index j -> end index ; Map 1 to hash frequency of all elements in subarray ; Map 2 to hash frequency of all frequencies of elements ; ele_count is the previous frequency of arr [ j ] ; Finding previous frequency of arr [ j ] in map 1 ; Increasing frequency of arr [ j ] by 1 ; Check if previous frequency is present in map 2 ; Delete previous frequency if hash is equal to 1 ; Decrement the hash of previous frequency ; Incrementing hash of new frequency in map 2 ; Check if map2 size is 1 and updating answer ; Return the maximum size of subarray ; Driver Code ; Given array arr [ ] ; Function Call
import java . util . * ; class GFG { static int max_subarray_size ( int N , int [ ] arr ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { HashMap < Integer , Integer > map1 = new HashMap < > ( ) ; HashMap < Integer , Integer > map2 = new HashMap < > ( ) ; for ( int j = i ; j < N ; j ++ ) { int ele_count ; if ( ! map1 . containsKey ( arr [ j ] ) ) { ele_count = 0 ; } else { ele_count = map1 . get ( arr [ j ] ) ; } if ( map1 . containsKey ( arr [ j ] ) ) { map1 . put ( arr [ j ] , map1 . get ( arr [ j ] ) + 1 ) ; } else { map1 . put ( arr [ j ] , 1 ) ; } if ( map2 . containsKey ( ele_count ) ) { if ( map2 . get ( ele_count ) == 1 ) { map2 . remove ( ele_count ) ; } else { map2 . put ( ele_count , map2 . get ( ele_count ) - 1 ) ; } } if ( map2 . containsKey ( ele_count + 1 ) ) { map2 . put ( ele_count + 1 , map2 . get ( ele_count + 1 ) + 1 ) ; } else { map2 . put ( ele_count + 1 , 1 ) ; } if ( map2 . size ( ) == 1 ) ans = Math . max ( ans , j - i + 1 ) ; } } return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 2 , 5 , 6 , 5 , 6 } ; int N = arr . length ; System . out . println ( max_subarray_size ( N , arr ) ) ; } }