Maximize frequency of an element by at most one increment or decrement of all array elements | Java program to implement the above approach ; 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
import java . util . Arrays ; class GFG { static void max_freq ( int arr [ ] , int N ) { Arrays . sort ( arr ) ; int Max = arr [ N - 1 ] ; int Min = arr [ 0 ] ; int freq [ ] = new int [ Max - Min + 1 ] ; for ( int i = 0 ; i < N ; i ++ ) { freq [ arr [ i ] - Min ] ++ ; } int maxSum = 0 ; for ( int i = 0 ; i < ( Max - Min - 1 ) ; i ++ ) { int val = freq [ i ] + freq [ i + 1 ] + freq [ i + 2 ] ; maxSum = Math . max ( maxSum , val ) ; } System . out . println ( maxSum ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 1 , 4 , 1 , 5 , 9 , 2 } ; int N = arr . length ; max_freq ( arr , N ) ; } }