|
| 1 | +// Source : https://leetcode.com/problems/frequency-of-the-most-frequent-element/ |
| 2 | +// Author : Hao Chen |
| 3 | +// Date : 2021-04-25 |
| 4 | + |
| 5 | +/***************************************************************************************************** |
| 6 | + * |
| 7 | + * The frequency of an element is the number of times it occurs in an array. |
| 8 | + * |
| 9 | + * You are given an integer array nums and an integer k. In one operation, you can choose an index of |
| 10 | + * nums and increment the element at that index by 1. |
| 11 | + * |
| 12 | + * Return the maximum possible frequency of an element after performing at most k operations. |
| 13 | + * |
| 14 | + * Example 1: |
| 15 | + * |
| 16 | + * Input: nums = [1,2,4], k = 5 |
| 17 | + * Output: 3 |
| 18 | + * Explanation: Increment the first element three times and the second element two times to make nums |
| 19 | + * = [4,4,4]. |
| 20 | + * 4 has a frequency of 3. |
| 21 | + * |
| 22 | + * Example 2: |
| 23 | + * |
| 24 | + * Input: nums = [1,4,8,13], k = 5 |
| 25 | + * Output: 2 |
| 26 | + * Explanation: There are multiple optimal solutions: |
| 27 | + * - Increment the first element three times to make nums = [4,4,8,13]. 4 has a frequency of 2. |
| 28 | + * - Increment the second element four times to make nums = [1,8,8,13]. 8 has a frequency of 2. |
| 29 | + * - Increment the third element five times to make nums = [1,4,13,13]. 13 has a frequency of 2. |
| 30 | + * |
| 31 | + * Example 3: |
| 32 | + * |
| 33 | + * Input: nums = [3,9,6], k = 2 |
| 34 | + * Output: 1 |
| 35 | + * |
| 36 | + * Constraints: |
| 37 | + * |
| 38 | + * 1 <= nums.length <= 10^5 |
| 39 | + * 1 <= nums[i] <= 10^5 |
| 40 | + * 1 <= k <= 10^5 |
| 41 | + ******************************************************************************************************/ |
| 42 | + |
| 43 | +class Solution { |
| 44 | +public: |
| 45 | + int maxFrequency(vector<int>& nums, int k) { |
| 46 | + sort(nums.begin(), nums.end()); |
| 47 | + int m = 1; |
| 48 | + int start = 0; |
| 49 | + int i = 1; |
| 50 | + for(; i<nums.size(); i++){ |
| 51 | + long delta = nums[i] - nums[i-1]; |
| 52 | + k -= delta * (i - start);; |
| 53 | + if (k < 0 ) { |
| 54 | + // remove the first one |
| 55 | + k += (nums[i] - nums[start]) ; |
| 56 | + start++; |
| 57 | + } |
| 58 | + m = max(m, i - start +1); |
| 59 | + |
| 60 | + } |
| 61 | + return m; |
| 62 | + } |
| 63 | +}; |
0 commit comments