Maximize distinct elements by incrementing / decrementing an element or keeping it same | Function that Maximize the count of distinct element ; Sort thr list ; Keeping track of previous change ; Decrement is possible ; Remain as it is ; Increment is possible ; Driver Code
def max_dist_ele ( arr , n ) : NEW_LINE INDENT arr . sort ( ) NEW_LINE ans = 0 NEW_LINE prev = 0 NEW_LINE for i in range ( n ) : NEW_LINE INDENT if prev < ( arr [ i ] - 1 ) : NEW_LINE INDENT ans += 1 ; NEW_LINE prev = arr [ i ] - 1 NEW_LINE DEDENT elif prev < ( arr [ i ] ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr [ i ] NEW_LINE DEDENT elif prev < ( arr [ i ] + 1 ) : NEW_LINE INDENT ans += 1 NEW_LINE prev = arr [ i ] + 1 NEW_LINE DEDENT DEDENT return ans NEW_LINE DEDENT arr = [ 1 , 1 , 1 , 8 , 8 , 8 , 9 , 9 ] NEW_LINE n = len ( arr ) NEW_LINE print ( max_dist_ele ( arr , n ) ) NEW_LINE