Largest subarray with frequency of all elements same | C ++ 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
#include <iostream> NEW_LINE #include <unordered_map> NEW_LINE using namespace std ; int max_subarray_size ( int N , int arr [ ] ) { int ans = 0 ; for ( int i = 0 ; i < N ; i ++ ) { unordered_map < int , int > map1 ; unordered_map < int , int > map2 ; for ( int j = i ; j < N ; j ++ ) { int ele_count ; if ( map1 . find ( arr [ j ] ) == map1 . end ( ) ) { ele_count = 0 ; } else { ele_count = map1 [ arr [ j ] ] ; } map1 [ arr [ j ] ] ++ ; if ( map2 . find ( ele_count ) != map2 . end ( ) ) { if ( map2 [ ele_count ] == 1 ) { map2 . erase ( ele_count ) ; } else { map2 [ ele_count ] -- ; } } map2 [ ele_count + 1 ] ++ ; if ( map2 . size ( ) == 1 ) ans = max ( ans , j - i + 1 ) ; } } return ans ; } int main ( ) { int arr [ ] = { 1 , 2 , 2 , 5 , 6 , 5 , 6 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << max_subarray_size ( N , arr ) ; return 0 ; }