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 nums[i] 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 nums[0] by 1. The resulting array is [2,2,6,4].
  • Choose i = 3, and decrease the value of nums[3] by 1. The resulting array is [2,2,6,3].
  • Choose i = 3, and decrease the value of nums[3] 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 <= nums[i] <= 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;
    }
};
相关推荐
会开花的二叉树3 分钟前
分布式文件存储 RPC 服务实现
c++·分布式·网络协议·rpc
文艺倾年3 分钟前
【八股消消乐】手撕分布式协议和算法(基础篇)
分布式·算法
abcd_zjq20 分钟前
VS2026+QT6.9+opencv图像增强(多帧平均降噪)(CLAHE对比度增强)(边缘增强)(图像超分辨率)
c++·图像处理·qt·opencv·visual studio
万岳科技系统开发39 分钟前
从源码优化外卖配送系统:算法调度、智能推荐与数据分析应用
算法·数据挖掘·数据分析
Algebraaaaa1 小时前
Qt中的字符串宏 | 编译期检查和运行期检查 | Qt信号与槽connect写法
开发语言·c++·qt
信奥卷王3 小时前
[GESP202503 五级] 原根判断
java·数据结构·算法
兮山与3 小时前
算法4.0
算法
nju_spy3 小时前
力扣每日一题(二)任务安排问题 + 区间变换问题 + 排列组合数学推式子
算法·leetcode·二分查找·贪心·排列组合·容斥原理·最大堆
初听于你3 小时前
高频面试题解析:算法到数据库全攻略
数据库·算法
翟天保Steven3 小时前
ITK-基于Mattes互信息的二维多模态配准算法
算法