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;
    }
};
相关推荐
北域码匠2 小时前
高通滤波算法深度解析(High-Pass Filter)
stm32·算法·c#·数字信号处理·嵌入式开发·滤波算法·高通滤波
指掀涛澜天下惊2 小时前
强化学习进阶篇八 策略梯度算法
深度学习·学习·算法·强化学习
乌萨奇也要立志学C++2 小时前
【洛谷】kmp算法
开发语言·算法
禹凕2 小时前
Dijkstra算法详解与应用
python·算法
千谦阙听3 小时前
C++类和对象(中):默认成员函数、构造与析构、拷贝构造、运算符重载
开发语言·c++·学习
YaraMemo3 小时前
元启发式算法框架
人工智能·算法·5g·信息与通信·启发式算法·信号处理
weixin_307779134 小时前
一维无粘 Burgers 方程的激波形成问题:MacCormack 格式求解
c++·算法·matlab
HugoStudio_SWAN4 小时前
洛谷 B4500 / B4449 / B3843 凯撒密码、密码强度与密码合规——加密与安全的三道门
c++·学习·程序人生·算法·安全
雾里看山5 小时前
源码目录、构建目录与 out-of-source build
c++·软件构建·cmake
枫叶林FYL5 小时前
【群体智能集群控制工程实践】第3章 一致性协同算法
算法