Maximizing the elements with a [ i + 1 ] > a [ i ] | C ++ implementation of the approach ; returns the number of positions where A ( i + 1 ) is greater than A ( i ) after rearrangement of the array ; Creating a HashMap containing char as a key and occurrences as a value ; Find the maximum frequency ; Driver code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int countMaxPos ( int arr [ ] , int n ) { unordered_map < int , int > map ; for ( int i = 0 ; i < n ; i ++ ) { if ( map . count ( arr [ i ] ) ) map . insert ( { arr [ i ] , ( map . count ( arr [ i ] ) + 1 ) } ) ; else map . insert ( { arr [ i ] , 1 } ) ; } int max_freq = 0 ; for ( auto i : map ) { if ( max_freq < i . second ) { max_freq = i . second ; } } return n - max_freq ; } int main ( ) { int arr [ ] = { 20 , 30 , 10 , 50 , 40 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << ( countMaxPos ( arr , n ) ) ; }