Maximize distinct elements by incrementing / decrementing an element or keeping it same | C # 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
using System ; class GFG { static int max_dist_ele ( int [ ] arr , int n ) { Array . 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 ; Console . WriteLine ( max_dist_ele ( arr , n ) ) ; } }