1966. Frequency Of The Most Frequent Element¶
Difficulty: Medium
LeetCode Problem View on GitHub
1966. Frequency of the Most Frequent Element
Medium
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 <= 1051 <= nums[i] <= 1051 <= k <= 105
Solution¶
class Solution {
public int maxFrequency(int[] nums, int k) {
int n = nums.length;
Arrays.sort(nums);
int low = 1, high = n, ans = 1;
while (low <= high) {
int mid = low + (high - low) / 2;
if (ok(mid, nums, k)) {
ans = mid;
low = mid + 1;
}
else high = mid - 1;
}
return ans;
}
private boolean ok(int mid, int arr[], int k) {
int n = arr.length;
long current_sum = 0;
for (int i = 0; i < mid; i++) current_sum += arr[i];
long req = arr[mid - 1] * 1L * mid;
long left = req - current_sum;
if (left <= k) return true;
int start = 0;
for (int i = mid; i < n; i++) {
current_sum += arr[i];
current_sum -= arr[start];
req = arr[i] * 1L * mid;
left = req - current_sum;
if (left <= k) return true;
start++;
}
return false;
}
}
Complexity Analysis¶
- Time Complexity:
O(?) - Space Complexity:
O(?)
Approach¶
Detailed explanation of the approach will be added here