Maximize frequency of an element by at most one increment or decrement of all array elements | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; void max_freq ( int arr [ ] , int N ) { int Max = * max_element ( arr , arr + N ) ; int Min = * min_element ( arr , arr + N ) ; int freq [ Max - Min + 1 ] = { 0 } ; 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 = max ( maxSum , val ) ; } cout << maxSum << " STRNEWLINE " ; } int main ( ) { int arr [ ] = { 3 , 1 , 4 , 1 , 5 , 9 , 2 } ; int N = sizeof ( arr ) / sizeof ( arr [ 0 ] ) ; max_freq ( arr , N ) ; return 0 ; }