Maximum frequency of any array element possible by exactly K increments

Given an array arr[] consisting of N positive integers and an integer K, the task is to find the highest frequency of any array element after performing exactly K increments.
Examples:
Input: arr[] = {1, 3, 2, 2}, K = 2
Output: 3
Explanation:
Below are the operations performed:
- Add 1 to the element at index 2(= 2), then the array modifies to {1, 3, 3, 2}.
- Add 1 to the element at index 3(= 2), then the array modifies to {1, 3, 3, 3}.
After the above steps, the maximum frequency of an array element is 3.
Input: arr[] = {4, 3, 4}, K = 5
Output: 2
Approach: The given problem can be solved by using the Sliding Window Technique and Sorting. Follow the steps below to solve this problem:
- Initialize the variables say start, end, sum as 0, and mostFreq as INT_MIN.
- Sort the array arr[] in increasing order.
- Iterate over the range [0, N – 1] using the variable end and perform the following steps:
- Increment the value of sum by the value arr[end].
- While the value of (sum + K) is less than the value of (arr[end] * (end – start+ 1)), then decrement the value of the sum by arr[start] and increment the value of start by 1.
- Update the value of mostFreq to the maximum of mostFreq and (end – start + 1).
- Initialize a variable, say reqSum as the value of (arr[N-1] * N – sum) that stores the resultant sum to make all the array elements equal.
- If the value of mostFreq is N and the value of K is greater than reqSum, then decrement the value of K by reqSum.
- If the value of K is a multiple of N, then print N. Otherwise, print the value of (N – 1).
- After completing the above steps, print the value of mostFreq as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approachÂ
#include <bits/stdc++.h>using namespace std;Â
// Function to find the highest frequency// of any array element possible by// exactly K increment operationsvoid findMostFrequent(int arr[], int N,                      int K){    int start = 0, end = 0;Â
    // Sort the given array    sort(arr, arr + N);Â
    // Stores the maximum frequency    // and the sum of sliding window    int mostFreq = INT_MIN, sum = 0;Â
    // Traverse the array arr[]    for (end = 0; end < N; end++) {Â
        // Add the current element        // to the window        sum = sum + arr[end];Â
        // Decreasing the window size        while (sum + K < arr[end] * (end - start + 1)) {Â
            // Update the value of sum            // by subtracting arr[start]            sum = sum - arr[start];Â
            // Increment the value            // of the start            start++;        }Â
        // Update maximum window size        mostFreq = max(mostFreq,                       end - start + 1);    }Â
    // Stores the required sum to    // make all elements of arr[] equal    int reqSum = arr[N - 1] * N - sum;Â
    // If result from at most K increments    // is N and K is greater than reqSum    if (mostFreq == N && reqSum < K) {Â
        // Decrement the value of K        // by reqSum        K = K - reqSum;Â
        // If K is multiple of N then        // increment K/N times to        // every element        if (K % N == 0) {            cout << N << endl;        }Â
        // Otherwise first make every        // element equal then increment        // remaining K to one element        else {            cout << N - 1 << endl;        }Â
        return;    }Â
    // Print the answer    cout << mostFreq << endl;}Â
// Driver Codeint main(){Â Â Â Â int arr[] = { 4, 3, 4 };Â Â Â Â int K = 5;Â Â Â Â int N = sizeof(arr) / sizeof(arr[0]);Â Â Â Â findMostFrequent(arr, N, K);Â
    return 0;} |
Java
// Java program for the above approachÂ
import java.util.*;Â
class GFG {Â
// Function to find the highest frequency// of any array element possible by// exactly K increment operationsstatic void findMostFrequent(int arr[], int N,                      int K){    int start = 0, end = 0;Â
    // Sort the given array    Arrays.sort(arr);Â
    // Stores the maximum frequency    // and the sum of sliding window    int mostFreq = Integer.MIN_VALUE, sum = 0;Â
    // Traverse the array arr[]    for (end = 0; end < N; end++) {Â
        // Add the current element        // to the window        sum = sum + arr[end];Â
        // Decreasing the window size        while (sum + K < arr[end] * (end - start + 1)) {Â
            // Update the value of sum            // by subtracting arr[start]            sum = sum - arr[start];Â
            // Increment the value            // of the start            start++;        }Â
        // Update maximum window size        mostFreq = Math.max(mostFreq,                       end - start + 1);    }Â
    // Stores the required sum to    // make all elements of arr[] equal    int reqSum = arr[N - 1] * N - sum;Â
    // If result from at most K increments    // is N and K is greater than reqSum    if (mostFreq == N && reqSum < K) {Â
        // Decrement the value of K        // by reqSum        K = K - reqSum;Â
        // If K is multiple of N then        // increment K/N times to        // every element        if (K % N == 0) {            System.out.println(N);        }Â
        // Otherwise first make every        // element equal then increment        // remaining K to one element        else {            System.out.println(N - 1);        }Â
        return;    }Â
    // Print the answer    System.out.println( mostFreq);}Â
    // Driver Code    public static void main(String[] args)    {    int arr[] = { 4, 3, 4 };    int K = 5;    int N = arr.length;    findMostFrequent(arr, N, K);    }}Â
// This code is contributed by target_2. |
Python3
# Python program for the above approachÂ
# Function to find the highest frequency# of any array element possible by# exactly K increment operationsdef findMostFrequent( arr, N, K):    start = 0    end = 0         # Sort the given array    arr.sort()         # Stores the maximum frequency    # and the sum of sliding window    mostFreq = -2**31    sum = 0         # Traverse the array arr[]    for end in range(N):                 # Add the current element        # to the window        sum = sum + arr[end]                 # Decreasing the window size        while (sum + K < arr[end] * (end - start + 1)):                         # Update the value of sum            # by subtracting arr[start]            sum = sum - arr[start]                         # Increment the value            # of the start            start += 1                     # Update maximum window size        mostFreq = max(mostFreq, end - start + 1)             # Stores the required sum to    # make all elements of arr[] equal    reqSum = arr[N - 1] * N - sum         # If result from at most K increments    # is N and K is greater than reqSum    if (mostFreq == N and reqSum < K):                 # Decrement the value of K        # by reqSum        K = K - reqSum                 # If K is multiple of N then        # increment K/N times to        # every element        if (K % N == 0):            print(N)                     # Otherwise first make every        # element equal then increment        # remaining K to one element        else:            print(N - 1)        return    # Print the answer    print(mostFreq)Â
# Driver Codearr = [4, 3, 4]K = 5N = len(arr)findMostFrequent(arr, N, K)Â
# This code is contributed by shubhamsingh10 |
C#
// C# program for the above approachusing System;Â
class GFG{Â
// Function to find the highest frequency// of any array element possible by// exactly K increment operationsstatic void findMostFrequent(int []arr, int N,                             int K){    int start = 0, end = 0;Â
    // Sort the given array    Array.Sort(arr);Â
    // Stores the maximum frequency    // and the sum of sliding window    int mostFreq = Int32.MinValue, sum = 0;Â
    // Traverse the array arr[]    for(end = 0; end < N; end++)    {                 // Add the current element        // to the window        sum = sum + arr[end];Â
        // Decreasing the window size        while (sum + K < arr[end] * (end - start + 1))        {                         // Update the value of sum            // by subtracting arr[start]            sum = sum - arr[start];Â
            // Increment the value            // of the start            start++;        }Â
        // Update maximum window size        mostFreq = Math.Max(mostFreq,                            end - start + 1);    }Â
    // Stores the required sum to    // make all elements of arr[] equal    int reqSum = arr[N - 1] * N - sum;Â
    // If result from at most K increments    // is N and K is greater than reqSum    if (mostFreq == N && reqSum < K)     {                 // Decrement the value of K        // by reqSum        K = K - reqSum;Â
        // If K is multiple of N then        // increment K/N times to        // every element        if (K % N == 0)         {            Console.Write(N);        }Â
        // Otherwise first make every        // element equal then increment        // remaining K to one element        else        {            Console.Write(N - 1);        }        return;    }Â
    // Print the answer    Console.Write( mostFreq);}Â
// Driver Codepublic static void Main(String[] args){Â Â Â Â int []arr = { 4, 3, 4 };Â Â Â Â int K = 5;Â Â Â Â int N = arr.Length;Â Â Â Â Â Â Â Â Â findMostFrequent(arr, N, K);}}Â
// This code is contributed by shivanisinghss2110 |
Javascript
<script>Â
// Javascript program for the above approachÂ
// Function to find the highest frequency// of any array element possible by// exactly K increment operationsfunction findMostFrequent(arr, N, K) {Â Â Â Â let start = 0, end = 0;Â
    // Sort the given array    arr.sort((a, b) => a - b);Â
    // Stores the maximum frequency    // and the sum of sliding window    let mostFreq = Number.MIN_SAFE_INTEGER, sum = 0;Â
    // Traverse the array arr[]    for (end = 0; end < N; end++) {Â
        // Add the current element        // to the window        sum = sum + arr[end];Â
        // Decreasing the window size        while (sum + K < arr[end] * (end - start + 1)) {Â
            // Update the value of sum            // by subtracting arr[start]            sum = sum - arr[start];Â
            // Increment the value            // of the start            start++;        }Â
        // Update maximum window size        mostFreq = Math.max(mostFreq,            end - start + 1);    }Â
    // Stores the required sum to    // make all elements of arr[] equal    let reqSum = arr[N - 1] * N - sum;Â
    // If result from at most K increments    // is N and K is greater than reqSum    if (mostFreq == N && reqSum < K) {Â
        // Decrement the value of K        // by reqSum        K = K - reqSum;Â
        // If K is multiple of N then        // increment K/N times to        // every element        if (K % N == 0) {            document.write(N + "<br>");        }Â
        // Otherwise first make every        // element equal then increment        // remaining K to one element        else {            document.write(N - 1 + "<br>");        }Â
        return;    }Â
    // Print the answer    document.write(mostFreq + "<br>");}Â
// Driver Codelet arr = [4, 3, 4];let K = 5;let N = arr.lengthfindMostFrequent(arr, N, K);Â
// This code is contributed by _saurabh_jaiswal.</script> |
Output:Â
2
Â
Time Complexity: O(N * log N)
Auxiliary Space: O(1)
Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



