Maximize frequency of an element by at most one increment or decrement of all array elements | Function to maximize the frequency of an array element by incrementing or decrementing array elements at most once ; Stores the largest array element ; Stores the smallest array element ; freq [ i ] : Stores frequency of ( i + Min ) in the array ; Traverse the array ; Update frequency of arr [ i ] ; Stores maximum frequency of an array element by incrementing or decrementing array elements ; Iterate all the numbers over the range [ Min , Max ] ; Stores sum of three consecutive numbers ; Update maxSum ; Print maxSum ; Driver Code ; Function call
def max_freq ( arr , N ) : NEW_LINE INDENT Max = max ( arr ) NEW_LINE Min = min ( arr ) NEW_LINE freq = [ 0 ] * ( Max - Min + 1 ) NEW_LINE for i in range ( N ) : NEW_LINE INDENT freq [ arr [ i ] - Min ] += 1 NEW_LINE DEDENT maxSum = 0 NEW_LINE for i in range ( Max - Min - 1 ) : NEW_LINE INDENT val = freq [ i ] + freq [ i + 1 ] + freq [ i + 2 ] NEW_LINE maxSum = max ( maxSum , val ) NEW_LINE DEDENT print ( maxSum ) NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 1 , 4 , 1 , 5 , 9 , 2 ] NEW_LINE N = len ( arr ) NEW_LINE max_freq ( arr , N ) NEW_LINE DEDENT