Skip to content

Commit a3103f0

Browse files
1838 medium sliding window sorting great
1838. Frequency of the Most Frequent Element Solved Medium Topics Companies Hint 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 <= 105 1 <= nums[i] <= 105 1 <= k <= 105 Seen this question in a real interview before? 1/5 Yes No Accepted 150.7K Submissions 339.3K Acceptance Rate 44.4% Topics Companies Hint 1 Note that you can try all values in a brute force manner and find the maximum frequency of that value. Hint 2 To find the maximum frequency of a value consider the biggest elements smaller than or equal to this value
1 parent f1f8858 commit a3103f0

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed
+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
class Solution {
2+
public int maxFrequency(int[] nums, int k) {
3+
Arrays.sort(nums);
4+
int l=0,r=0;
5+
long total=0,ans=0;
6+
while(r<nums.length){
7+
total+=nums[r];
8+
//if window invalid
9+
while(nums[r]*(r-l+1L)>total+k){
10+
total-=nums[l];
11+
l+=1;
12+
}
13+
ans=Math.max(ans,r-l+1L);
14+
r+=1;
15+
}
16+
return (int) ans;
17+
}
18+
}

0 commit comments

Comments
 (0)