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;
    }
};
相关推荐
yi0114 分钟前
DAY19: LeetCode 28 找出字符串中第一个匹配项的下标
人工智能·笔记·python·算法·leetcode
不会就选b7 分钟前
算法日常・每日刷题--<动态规划>6
数据结构·算法·leetcode
释厄62310 分钟前
AI犯错即异质论——正确认知=免疫与安全防控技术算法
大数据·算法·安全
漂流瓶jz11 分钟前
UVA-12545 比特变换器 题解答案代码 算法竞赛入门经典第二版
数据结构·算法·题解·aoapc·算法竞赛入门经典·uva·12545
积流成海24 分钟前
哈希碰撞攻击全解析:从MD5到SHA1的安全演进史
算法·安全·哈希算法·哈希函数·盘子工具站·哈希计算
重生之小比特26 分钟前
【C++进阶】02 Linux基本指令
java·数据库·c++
v:PLLucky2026 分钟前
眼部疾病智能检测系统
算法·yolo·机器学习·百度·facebook
Omics Pro27 分钟前
00后大3休学创业!AI虚拟细胞
大数据·数据库·人工智能·算法·机器学习·自然语言处理
HEJOO929 分钟前
Go 语言结构体定义与实例详解
开发语言·算法·golang
(Charon)31 分钟前
【C++面试】手写智能指针(一):从unique_ptr理解独占所有权与移动语义
开发语言·c++