LeetCode2968. Apply Operations to Maximize Frequency Score

文章目录

一、题目

You are given a 0-indexed integer array nums and an integer k.

You can perform the following operation on the array at most k times:

Choose any index i from the array and increase or decrease numsi by 1.

The score of the final array is the frequency of the most frequent element in the array.

Return the maximum score you can achieve.

The frequency of an element is the number of occurences of that element in the array.

Example 1:

Input: nums = 1,2,6,4, k = 3

Output: 3

Explanation: We can do the following operations on the array:

  • Choose i = 0, and increase the value of nums0 by 1. The resulting array is 2,2,6,4.
  • Choose i = 3, and decrease the value of nums3 by 1. The resulting array is 2,2,6,3.
  • Choose i = 3, and decrease the value of nums3 by 1. The resulting array is 2,2,6,2.
    The element 2 is the most frequent in the final array so our score is 3.
    It can be shown that we cannot achieve a better score.
    Example 2:

Input: nums = 1,4,4,2,4, k = 0

Output: 3

Explanation: We cannot apply any operations so our score will be the frequency of the most frequent element in the original array, which is 3.

Constraints:

1 <= nums.length <= 105

1 <= numsi <= 109

0 <= k <= 1014

二、题解

cpp 复制代码
class Solution {
public:
    long long times(vector<int>& nums,vector<long long>& s,int l,int r,int i){
        long long leftTime = (long long) nums[i] * (i-l) - (s[i] - s[l]);
        long long rightTime = s[r+1] - s[i+1] - (long long)nums[i] * (r-i);
        return leftTime + rightTime;
    }
    int maxFrequencyScore(vector<int>& nums, long long k) {
        sort(nums.begin(),nums.end());
        int n = nums.size();
        //前缀和
        vector<long long> s(n+1,0);
        for(int i = 0;i < n;i++){
            s[i+1] = s[i] + nums[i];
        }
        int res = 0,left = 0;
        for(int right = 0;right < n;right++){
            while(times(nums,s,left,right,(left + right) / 2) > k) left++;
            res = max(res,right - left + 1);
        }
        return res;
    }
};
相关推荐
文心快码BaiduComate3 小时前
文心快码荣获“中国优秀软件产品”,实力再获国家级认可
算法·代码规范
玖玥拾4 小时前
LeetCode 189 轮转数组
算法·leetcode
ZhangShao06074 小时前
题解:CF2249B
c++·算法
小玮看世界4 小时前
[Python]线段树与二分法
数据结构·算法
吹什么轩5 小时前
c++复习:map和set的使用
开发语言·c++
fpcc6 小时前
跟我学C++中级篇—内存流
开发语言·c++
Tisfy6 小时前
LeetCode 3345.最小可整除数位乘积 I:暴力枚举(从n开始尝试)
数学·算法·leetcode·题解·枚举
DolphinDB智臾科技6 小时前
告别 TB 级数据搬运:DolphinDB 滤波算法库,重塑物联网数据价值链
物联网·算法
吹什么轩7 小时前
c++复习:模拟实现list来更好的理解和应用list
开发语言·c++
AmyLin_20017 小时前
PDF 色彩保真工程实践【5】核心实现(下):拼装 Image XObject、页面资源与内容流
c++·pdf·sdk·颜色空间·印刷·icc·cmyk