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;
    }
};
相关推荐
钱彬 (Qian Bin)27 分钟前
一文掌握工业缺陷检测项目实战(Pytorch算法训练、部署、C++ DLL制作、Qt集成)
c++·pytorch·python·qt·实战·工业缺陷检测·faster rcnn
努力努力再努力wz36 分钟前
【c++进阶系列】:万字详解AVL树(附源码实现)
java·运维·开发语言·c++·redis
Miraitowa_cheems44 分钟前
LeetCode算法日记 - Day 34: 二进制求和、字符串相乘
java·算法·leetcode·链表·职场和发展
wan5555cn1 小时前
AI生成内容的版权问题解析与实操指南
人工智能·笔记·深度学习·算法·音视频
小张成长计划..1 小时前
C++基础知识
c++
CHANG_THE_WORLD1 小时前
C++并发编程指南 std::promise 介绍与使用
java·开发语言·c++·promise
今后1231 小时前
【数据结构】带哨兵位双向循环链表
数据结构·链表
Lee嘉图1 小时前
数据结构——队列(Java)
数据结构
DDAshley1262 小时前
【PaddleOCR】从零开始训练自己的模型--详细教程
算法·计算机视觉