Distinct adjacent elements in an array | Java 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
import java . io . * ; import java . util . HashMap ; import java . util . Map ; class GFG { static void distinctAdjacentElement ( int a [ ] , int n ) { HashMap < Integer , Integer > m = new HashMap < Integer , Integer > ( ) ; for ( int i = 0 ; i < n ; ++ i ) { if ( m . containsKey ( a [ i ] ) ) { int x = m . get ( a [ i ] ) + 1 ; m . put ( a [ i ] , x ) ; } else { m . put ( a [ i ] , 1 ) ; } } int mx = 0 ; for ( int i = 0 ; i < n ; ++ i ) if ( mx < m . get ( a [ i ] ) ) mx = m . get ( a [ i ] ) ; if ( mx > ( n + 1 ) / 2 ) System . out . println ( " NO " ) ; else System . out . println ( " YES " ) ; } public static void main ( String [ ] args ) { int a [ ] = { 7 , 7 , 7 , 7 } ; int n = 4 ; distinctAdjacentElement ( a , n ) ; } }