标签:13 nums runner 1838 element Most frequency Element times
原题链接在这里:https://leetcode.com/problems/frequency-of-the-most-frequent-element/
题目:
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
题解:
Try to put similar elements together. Sort the array.
Use sliding window. When sum + k >= max * windows size. Then the whole window could be max after k operations.
Time Complexity: O(nlogn). n = nums.length.
Space: O(1).
AC Java:
1 class Solution { 2 public int maxFrequency(int[] nums, int k) { 3 if(nums == null || nums.length == 0){ 4 return 0; 5 } 6 7 Arrays.sort(nums); 8 int walker = 0; 9 int runner = 0; 10 long sum = 0; 11 int res = 0; 12 while(runner < nums.length){ 13 sum += nums[runner]; 14 while(sum + k < (long)nums[runner] * (runner - walker + 1)){ 15 sum -= nums[walker++]; 16 } 17 18 res = Math.max(res, runner - walker + 1); 19 runner++; 20 } 21 22 return res; 23 } 24 }
标签:13,nums,runner,1838,element,Most,frequency,Element,times 来源: https://www.cnblogs.com/Dylan-Java-NYC/p/16552852.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。