text: Distinct adjacent elements in an array | C ++ program to check if we can make neighbors distinct . ; map used to count the frequency of each element occurring in the array ; In this loop we count the frequency of element through map m . ; mx store the frequency of element which occurs most in array . ; In this loop we calculate the maximum frequency and store it in variable mx . ; By swapping we can adjust array only when the frequency of the element which occurs most is less than or equal to ( n + 1 ) / 2 . ; Driver program to test the above function
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void distinctAdjacentElement ( int a [ ] , int n ) { map < int , int > m ; for ( int i = 0 ; i < n ; ++ i ) m [ a [ i ] ] ++ ; int mx = 0 ; for ( int i = 0 ; i < n ; ++ i ) if ( mx < m [ a [ i ] ] ) mx = m [ a [ i ] ] ; if ( mx > ( n + 1 ) / 2 ) cout << " NO " << endl ; else cout << " YES " << endl ; } int main ( ) { int a [ ] = { 7 , 7 , 7 , 7 } ; int n = sizeof ( a ) / sizeof ( a [ 0 ] ) ; distinctAdjacentElement ( a , n ) ; return 0 ; }