Maximum frequency of any array element possible by at most K increments
Given an array arr[] of size N and an integer K, the task is to find the maximum possible frequency of any array element by at most K increments.
Examples:
Input: arr[] = {1, 4, 8, 13}, N = 4, K = 5
Output: 2
Explanation:
Incrementing arr[0] twice modifies arr[] to {4, 4, 8, 13}. Maximum frequency = 2.
Incrementing arr[1] four times modifies arr[] to {1, 8, 8, 13}. Maximum frequency = 2.
Incrementing arr[2] five times modifies arr[] to {1, 4, 13, 13}. Maximum frequency = 2.
Therefore, the maximum possible frequency of any array element that can be obtained by at most 5 increments is 2.
Input: arr[] = {2, 4, 5}, N = 3, K = 4
Output: 3
Approach: This problem can be solved by using Sliding Window Technique and Sorting. Follow the steps to solve this problem.
- Sort the array arr[].
- Initialize variables sum = 0, start = 0 and resultant frequency res = 0.
- Traverse the array over the range of indices [0, N – 1] and perform the following steps:
- Increment sum by arr[end].
- Iterate a loop until the value of [(end – start + 1) * arr[end] – sum] is less than K and perform the following operations:
- Decrement the value of sum by arr[start].
- Increment the value of start by 1.
- After completing the above steps, all the elements over the range [start, end] can be made equal by using at most K operations. Therefore, update the value of res as the maximum of res and (end – start + 1).
- Finally, print the value of res as frequency of most frequent element after performing Koperations.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void maxFrequency( int arr[], int N, int K)
{
sort(arr, arr + N);
int start = 0, end = 0;
int sum = 0, res = 0;
for (end = 0; end < N; end++) {
sum += arr[end];
while ((end - start + 1) * arr[end] - sum > K) {
sum -= arr[start];
start++;
}
res = max(res, end - start + 1);
}
cout << res << endl;
}
int main()
{
int arr[] = { 1, 4, 8, 13 };
int N = 4;
int K = 5;
maxFrequency(arr, N, K);
return 0;
}
|
Java
import java.util.Arrays;
class GFG{
static void maxFrequency( int arr[], int N, int K)
{
Arrays.sort(arr);
int start = 0 , end = 0 ;
int sum = 0 , res = 0 ;
for (end = 0 ; end < N; end++)
{
sum += arr[end];
while ((end - start + 1 ) *
arr[end] - sum > K)
{
sum -= arr[start];
start++;
}
res = Math.max(res, end - start + 1 );
}
System.out.println(res);
}
public static void main(String[] args)
{
int arr[] = { 1 , 4 , 8 , 13 };
int N = 4 ;
int K = 5 ;
maxFrequency(arr, N, K);
}
}
|
Python3
def maxFrequency(arr, N, K):
arr.sort()
start = 0
end = 0
sum = 0
res = 0
for end in range (N):
sum + = arr[end]
while ((end - start + 1 ) * arr[end] - sum > K):
sum - = arr[start]
start + = 1
res = max (res, end - start + 1 )
print (res)
if __name__ = = '__main__' :
arr = [ 1 , 4 , 8 , 13 ]
N = 4
K = 5
maxFrequency(arr, N, K)
|
C#
using System;
class GFG{
static void maxFrequency( int [] arr, int N, int K)
{
Array.Sort(arr);
int start = 0, end = 0;
int sum = 0, res = 0;
for (end = 0; end < N; end++)
{
sum += arr[end];
while ((end - start + 1) *
arr[end] - sum > K)
{
sum -= arr[start];
start++;
}
res = Math.Max(res, end - start + 1);
}
Console.WriteLine(res);
}
public static void Main()
{
int [] arr = { 1, 4, 8, 13 };
int N = 4;
int K = 5;
maxFrequency(arr, N, K);
}
}
|
Javascript
<script>
function maxFrequency(arr, N, K) {
arr.sort((a, b) => a - b);
let start = 0, end = 0;
let sum = 0, res = 0;
for (end = 0; end < N; end++) {
sum += arr[end];
while ((end - start + 1) * arr[end] - sum > K) {
sum -= arr[start];
start++;
}
res = Math.max(res, end - start + 1);
}
document.write(res + "<br>" );
}
let arr = [1, 4, 8, 13];
let N = 4;
let K = 5;
maxFrequency(arr, N, K);
</script>
|
Time Complexity: O(NlogN)
Auxiliary Space: O(1)
Approach: Using Binary Search
- Sort the input array in ascending order.
- Calculate prefix sums of the input array and store them in a vector.
- For each index in the sorted array, find the maximum frequency of the element at that index, such that we can change any number of elements to that element with a cost not exceeding k.
- The maximum frequency for all indices is the answer.
To find the maximum frequency of the element at a particular index:
- Start with a range of [0, index].
- For each iteration, find the middle point of the range.
- Calculate the sum of the elements from the middle point to the index using the prefix sums.
- Calculate the cost of changing all elements from the middle point to the index to the element at the current index.
- If the cost is less than or equal to k, move the left boundary of the range to the middle point.
- If the cost is greater than k, move the right boundary of the range to the middle point.
- Repeat steps 2-6 until the range is reduced to a single point.
- The frequency of the element is the difference between the index and the left boundary of the range plus one.
C++
#include <bits/stdc++.h>
using namespace std;
vector< long long > preSum;
int helper(vector< int >& nums, int k, int index)
{
int low = 0;
int high = index;
int res = index;
while (low <= high) {
int mid = low + (high - low) / 2;
long long s = preSum[index + 1] - preSum[mid];
if (s + k
>= ( long long )(index - mid + 1) * nums[index]) {
res = mid;
high = mid - 1;
}
else {
low = mid + 1;
}
}
return index - res + 1;
}
int maxFrequency(vector< int >& nums, int k)
{
sort(nums.begin(), nums.end());
int n = nums.size();
preSum.resize(n + 1);
for ( int i = 0; i < n; i++) {
preSum[i + 1] = preSum[i] + nums[i];
}
int ans = 0;
for ( int i = 0; i < n; i++) {
ans = max(ans, helper(nums, k, i));
}
return ans;
}
int main()
{
vector< int > arr = { 1, 4, 8, 13 };
int K = 5;
cout << "Frequency of the Most Frequent Element : "
<< maxFrequency(arr, K);
return 0;
}
|
Java
import java.util.*;
public class Main {
static List<Long> preSum = new ArrayList<>();
static int helper(List<Integer> nums, int k, int index)
{
int low = 0 ;
int high = index;
int res = index;
while (low <= high) {
int mid = low + (high - low) / 2 ;
long s
= preSum.get(index + 1 ) - preSum.get(mid);
if (s + k >= ( long )(index - mid + 1 )
* nums.get(index)) {
res = mid;
high = mid - 1 ;
}
else {
low = mid + 1 ;
}
}
return index - res + 1 ;
}
static int maxFrequency(List<Integer> nums, int k)
{
Collections.sort(nums);
int n = nums.size();
preSum = new ArrayList<>(
Collections.nCopies(n + 1 , 0L));
for ( int i = 0 ; i < n; i++) {
preSum.set(i + 1 , preSum.get(i) + nums.get(i));
}
int ans = 0 ;
for ( int i = 0 ; i < n; i++) {
ans = Math.max(ans, helper(nums, k, i));
}
return ans;
}
public static void main(String[] args)
{
List<Integer> arr = Arrays.asList( 1 , 4 , 8 , 13 );
int K = 5 ;
System.out.println(
"Frequency of the Most Frequent Element : "
+ maxFrequency(arr, K));
}
}
|
Python3
def helper(nums, k, index):
low = 0
high = index
res = index
while low < = high:
mid = low + (high - low) / / 2
s = sum (nums[mid:index + 1 ])
if s + k > = (index - mid + 1 ) * nums[index]:
res = mid
high = mid - 1
else :
low = mid + 1
return index - res + 1
def maxFrequency(nums, k):
nums.sort()
n = len (nums)
ans = 0
for i in range (n):
ans = max (ans, helper(nums, k, i))
return ans
if __name__ = = "__main__" :
arr = [ 1 , 4 , 8 , 13 ]
K = 5
print ( "Frequency of the Most Frequent Element:" , maxFrequency(arr, K))
|
C#
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static List< long > preSum = new List< long >();
static int Helper(List< int > nums, int k, int index)
{
int low = 0;
int high = index;
int res = index;
while (low <= high)
{
int mid = low + (high - low) / 2;
long s = preSum[index + 1] - preSum[mid];
if (s + k >= ( long )(index - mid + 1) * nums[index])
{
res = mid;
high = mid - 1;
}
else
{
low = mid + 1;
}
}
return index - res + 1;
}
static int MaxFrequency(List< int > nums, int k)
{
nums.Sort();
int n = nums.Count;
preSum = new List< long >( new long [n + 1]);
for ( int i = 0; i < n; i++)
{
preSum[i + 1] = preSum[i] + nums[i];
}
int ans = 0;
for ( int i = 0; i < n; i++)
{
ans = Math.Max(ans, Helper(nums, k, i));
}
return ans;
}
static void Main( string [] args)
{
List< int > arr = new List< int > { 1, 4, 8, 13 };
int K = 5;
Console.WriteLine( "Frequency of the Most Frequent Element: " + MaxFrequency(arr, K));
}
}
|
Javascript
function maxFrequency(nums, k) {
nums.sort((a, b) => a - b);
const n = nums.length;
const preSum = new Array(n + 1).fill(0);
for (let i = 0; i < n; i++) {
preSum[i + 1] = preSum[i] + nums[i];
}
function helper(index) {
let low = 0;
let high = index;
let res = index;
while (low <= high) {
const mid = low + Math.floor((high - low) / 2);
const s = preSum[index + 1] - preSum[mid];
if (s + k >= (index - mid + 1) * nums[index]) {
res = mid;
high = mid - 1;
} else {
low = mid + 1;
}
}
return index - res + 1;
}
let ans = 0;
for (let i = 0; i < n; i++) {
ans = Math.max(ans, helper(i));
}
return ans;
}
const arr = [1, 4, 8, 13];
const K = 5;
console.log( "Frequency of the Most Frequent Element: " + maxFrequency(arr, K));
|
Output
Frequency of the Most Frequent Element : 2
Time Complexity: O(NlogN) where N is the size of the input vector
Auxiliary Space: O(N) where N is the size of the input vector. This is because we need to store the prefix sum vector which has N+1 elements, and the input vector after sorting has n elements.
Last Updated :
25 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...