# LC 1838. Frequency of the Most Frequent Element ### [Problem link](https://leetcode.com/problems/frequency-of-the-most-frequent-element/) ###### tags: `leedcode` `medium` `c++` `Sliding Window` The **frequency** of an element is the number of times it occurs in an array. You are given an integer array <code>nums</code> and an integer <code>k</code>. In one operation, you can choose an index of <code>nums</code> and increment the element at that index by <code>1</code>. Return the **maximum possible frequency** of an element after performing **at most** <code>k</code> 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:** - <code>1 <= nums.length <= 10<sup>5</sup></code> - <code>1 <= nums[i] <= 10<sup>5</sup></code> - <code>1 <= k <= 10<sup>5</sup></code> ## Solution 1 - Sliding Window #### C++ ```cpp= class Solution { public: int maxFrequency(vector<int>& nums, int k) { sort(nums.begin(), nums.end()); long long oper = 0; int ans = 1; int l = 0; for (int r = 1; r < nums.size(); r++) { oper += (long long)(nums[r] - nums[r - 1]) * (r - l); while (oper > k) { oper -= nums[r] - nums[l]; l++; } ans = max(ans, r - l + 1); } return ans; } }; ``` >### Complexity >n = nums.length >| | Time Complexity | Space Complexity | >| ----------- | --------------- | ---------------- | >| Solution 1 | O(nlogn) | O(logn) | ## Note Sol1: Space Complexity: logn => 排序所需的空間