Frequency of the Most Frequent Element Problem
#1838
Try it yourself first
Five languages, sample and hidden tests, right in the browser.
Practice it as an interview
Talk through your solution with an AI interviewer while you code.
Description
LeetCode Problem 1838.
The frequency of an element is the number of times it occurs in an array.
You are given an integer array nums and an integer k. In one operation, you can choose an index of nums and increment the element at that index by 1.
Return the maximum possible frequency of an element after performing at most k operations.
Example 1:
Input: nums = [1,2,4], k = 5
Output: 3
Explanation: Increment the first element three times and the second element two times to make nums = [4,4,4].
4 has a frequency of 3.
Example 2:
Input: nums = [1,4,8,13], k = 5
Output: 2
Explanation: There are multiple optimal solutions:
- Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2.
- Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2.
- Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2.
Example 3:
Input: nums = [3,9,6], k = 2
Output: 1
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^51 <= k <= 10^5
Solution
Approach: Sort, Prefix Sums and Binary Search
Three observations:
- The most frequent value can be taken to be a number already in the array, since raising elements beyond the largest chosen one only costs more.
- The elements raised should form a contiguous window of the sorted array, and the window's largest element (the last one) is the target value.
- If a window of length
mcan be made equal with at mostkincrements, so can any shorter length. So we can binary search on the answer.
Sort nums and build prefix sums s. To check a length m, look at each window ending at index i: the cost to raise it all to nums[i - 1] is nums[i - 1] * m - (s[i] - s[i - m]). If any window costs at most k, the length is feasible.
Complexity: O(n log n) time and O(n) space.
class Solution:
def maxFrequency(self, nums: List[int], k: int) -> int:
def check(m: int) -> bool:
for i in range(m, n + 1):
if nums[i - 1] * m - (s[i] - s[i - m]) <= k:
return True
return False
n = len(nums)
nums.sort()
s = [0] * (n + 1)
for i in range(1, n + 1):
s[i] = s[i - 1] + nums[i - 1]
l, r = 1, n
while l < r:
mid = (l + r + 1) >> 1
if check(mid):
l = mid
else:
r = mid - 1
return l