[LeetCode] 1838. 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

最高频元素的频数。

元素的 频数 是该元素在一个数组中出现的次数。

给你一个整数数组 nums 和一个整数 k 。在一步操作中,你可以选择 nums 的一个下标,并将该下标对应元素的值增加 1 。

执行最多 k 次操作后,返回数组中最高频元素的 最大可能频数 。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/frequency-of-the-most-frequent-element
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

这道题我暂时提供一个滑动窗口的思路,而且滑动窗口的思路不是很容易意识到。注意题目的细节,你只能选择一个下标并且对 nums[i] 做加一的操作,并且你只被允许做 K 次操作,也就是说你只能对某一些元素做这个加一操作,一共可以做 K 次。但是对哪些元素做加一才做,做多少次,这就需要用到滑动窗口了。

首先我们需要对 input 数组排序,之后还是用经典的滑动窗口模板,给出 start 和 end 两个指针。对于 end 指针指向的元素 nums[end],我们可以把它视为一个target number,意思是我们试图把其他小于 nums[end] 的元素都通过加一操作变为 nums[end],从而使得 nums[end] 是出现次数最多的元素。对于 start 和 end 指针夹住的这一段元素,他们的加和很好算;但是如果他们的加和 sum + K次操作之后的和大于这一段计划中的和的话,则需要移动 start 指针缩短窗口的距离。通过这个方法我们可以算出符合条件的最大的子数组的长度。

最后注意数据范围,计算 sum 的时候要用 long 型。

时间O(nlogn)

空间O(1)

Java实现

 1 class Solution {
 2     public int maxFrequency(int[] nums, int k) {
 3         int res = 0;
 4         long sum = 0;
 5         int start = 0;
 6         int end = 0;
 7         Arrays.sort(nums);
 8         while (end < nums.length) {
 9             sum += nums[end];
10             while (sum + k < (long) nums[end] * (end - start + 1)) {
11                 sum -= nums[start];
12                 start++;
13             }
14             res = Math.max(res, end - start + 1);
15             end++;
16         }
17         return res;
18     }
19 }

sliding window相关题目

LeetCode 题目总结

原文地址:https://www.cnblogs.com/cnoodle/p/14702946.html