Problem · Array

Maximize Element Frequency

Learn this problem
MediumGoldman Sachs logoGoldman SachsFULLTIMEONSITE INTERVIEW

Problem statement

Given an array of positive integers nums and a positive integer k, you may perform at most k operations.

In one operation, choose one index and increase nums[i] by 1.

Return the maximum possible frequency of any value in the array after performing the operations. The frequency of a value is the number of times it appears.

Function

maxFrequency(nums: int[], k: int) → int

Examples

Example 1

nums = [1,3,5,7,8,9,10,15]k = 6return = 4

Increase 7 three times, 8 twice, and 9 once. The array then contains four occurrences of 10, using exactly 6 operations.

Example 2

nums = [1,2,4]k = 5return = 3

Increase 1 to 4 using 3 operations and increase 2 to 4 using 2 operations. All three elements become 4.

Example 3

nums = [1,4,8,13]k = 5return = 2

Two elements can be made equal, for example by increasing 8 to 13. Making any three elements equal requires more than 5 operations.

Example 4

nums = [3,9,6]k = 2return = 1

No value can reach another array value with only 2 increments, so the maximum frequency remains 1.

Constraints

  • 1 <= nums.length <= 10^5
  • 1 <= nums[i] <= 10^5
  • 1 <= k <= 10^5

More Goldman Sachs problems

drafts saved locally
public int maxFrequency(int[] nums, int k) {
    // write your code here
}
nums[1,3,5,7,8,9,10,15]
k6
expected4
checking account