LeetCode1838(2021.7.19)

LC1838. 最高频元素的频数

class Solution {
public:
    int maxFrequency(vector<int>& nums, int k) {
        sort(nums.begin(), nums.end());
        int n = nums.size(), l = 0, res = 1;
        long long total = 0;
        for (int r = 1; r < n; ++r) {
            total += (long long)(nums[r] - nums[r - 1]) * (r - l);
            while (total > k) total -= nums[r] - nums[l], l++;
            res = max(res, r - l + 1);
        }
        return res;
    }
};

发表评论