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 . ; Main Method
code: using System ; using System . Collections . Generic ; class GFG { public static void distinctAdjacentElement ( int [ ] a , int n ) { Dictionary < int , int > m = new Dictionary < int , int > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( m . ContainsKey ( a [ i ] ) ) { int x = m [ a [ i ] ] + 1 ; m [ a [ i ] ] = x ; } else { m [ a [ i ] ] = 1 ; } } int mx = 0 ; for ( int i = 0 ; i < n ; ++ i ) { if ( mx < m [ a [ i ] ] ) { mx = m [ a [ i ] ] ; } } if ( mx > ( n + 1 ) / 2 ) { Console . WriteLine ( " NO " ) ; } else { Console . WriteLine ( " YES " ) ; } } public static void Main ( string [ ] args ) { int [ ] a = new int [ ] { 7 , 7 , 7 , 7 } ; int n = 4 ; distinctAdjacentElement ( a , n ) ; } }