Maximize distinct elements by incrementing / decrementing an element or keeping it same | Java program to Maximize the count of distinct element ; Function that Maximize the count of distinct element ; sort thr array ; keeping track of previous change ; decrement is possible ; remain as it is ; increment is possible ; Driver Code
import java . util . * ; public class GFG { static int max_dist_ele ( int arr [ ] , int n ) { Arrays . sort ( arr ) ; int ans = 0 ; int prev = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( prev < ( arr [ i ] - 1 ) ) { ans ++ ; prev = arr [ i ] - 1 ; } else if ( prev < ( arr [ i ] ) ) { ans ++ ; prev = arr [ i ] ; } else if ( prev < ( arr [ i ] + 1 ) ) { ans ++ ; prev = arr [ i ] + 1 ; } } return ans ; } public static void main ( String args [ ] ) { int arr [ ] = { 1 , 1 , 1 , 8 , 8 , 8 , 9 , 9 } ; int n = arr . length ; System . out . println ( max_dist_ele ( arr , n ) ) ; } }