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 ; Prlet maxSum ; Driver Code ; Function call
function max_freq ( arr , N ) { arr . sort ( ) ; let Max = arr [ N - 1 ] ; let Min = arr [ 0 ] ; let freq = [ ] ; for ( let i = 0 ; i < Max - Min + 1 ; i ++ ) { freq [ i ] = 0 ; } for ( let i = 0 ; i < N ; i ++ ) { freq [ arr [ i ] - Min ] ++ ; } let maxSum = 0 ; for ( let i = 0 ; i < ( Max - Min - 1 ) ; i ++ ) { let val = freq [ i ] + freq [ i + 1 ] + freq [ i + 2 ] ; maxSum = Math . max ( maxSum , val ) ; } document . write ( maxSum ) ; } let arr = [ 3 , 1 , 4 , 1 , 5 , 9 , 2 ] ; let N = arr . length ; max_freq ( arr , N ) ;