Maximize distinct elements by incrementing / decrementing an element or keeping it same | C ++ program to Maximize distinct elements by incrementing / decrementing an element or keeping it same ; Function that Maximize the count of distinct element ; sort thr array ; keeping track of previous change ; check the decremented value ; check the current value ; check the incremented value ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; int max_dist_ele ( int arr [ ] , int n ) { sort ( arr , arr + n ) ; 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 ; } int main ( ) { int arr [ ] = { 1 , 1 , 1 , 8 , 8 , 8 , 9 , 9 } ; int n = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; cout << max_dist_ele ( arr , n ) << endl ; return 0 ; }