LeetCode //C - 1224. Maximum Equal Frequency

1224. Maximum Equal Frequency

Given an array nums of positive integers, return the longest possible length of an array prefix of nums, such that it is possible to remove exactly one element from this prefix so that every number that has appeared in it will have the same number of occurrences.

If after removing one element there are no remaining elements, it's still considered that every appeared number has the same number of ocurrences (0).

Example 1:

Input: nums = 2,2,1,1,5,3,3,5

Output: 7

Explanation: For the subarray 2,2,1,1,5,3,3 of length 7, if we remove nums4 = 5, we will get 2,2,1,1,3,3, so that each number will appear exactly twice.

Example 2:

Input: nums = 1,1,1,2,2,2,3,3,3,4,4,4,5

Output: 13

Constraints:
  • 2 < = n u m s . l e n g t h < = 10 5 2 <= nums.length <= 10^5 2<=nums.length<=105
  • 1 < = n u m s i < = 10 5 1 <= numsi <= 10^5 1<=numsi<=105

From: LeetCode

Link: 1224. Maximum Equal Frequency


Solution:

Ideas:

We can solve this in one pass by tracking two things: each value's frequency, and how many values currently have each frequency. The key is checking when the current prefix can be fixed by deleting exactly one number.

Code:
c 复制代码
int maxEqualFreq(int* nums, int numsSize) {
    int count[100001] = {0};   // count[x] = frequency of number x
    int freq[100002] = {0};    // freq[f] = how many numbers appear f times

    int ans = 0;
    int maxFreq = 0;

    for (int i = 0; i < numsSize; i++) {
        int x = nums[i];

        if (count[x] > 0) {
            freq[count[x]]--;
        }

        count[x]++;
        freq[count[x]]++;

        if (count[x] > maxFreq) {
            maxFreq = count[x];
        }

        int len = i + 1;

        /*
            Valid cases:

            1. maxFreq == 1
               Every number appears once.
               Remove any one element.

            2. One number appears maxFreq times,
               all others appear maxFreq - 1 times.
               Remove one occurrence from that number.

            3. One number appears once,
               all others appear maxFreq times.
               Remove that single-occurrence number.
        */
        if (maxFreq == 1 ||
            freq[maxFreq] == 1 &&
            freq[maxFreq] * maxFreq + freq[maxFreq - 1] * (maxFreq - 1) == len ||
            freq[1] == 1 &&
            freq[maxFreq] * maxFreq + 1 == len) {
            ans = len;
        }
    }

    return ans;
}
相关推荐
旺仔仔仔18 分钟前
机器人项目实战(5):从单次抓取,到接收指令连续做事
算法
旺仔仔仔26 分钟前
机器人项目实战(2):识别物体、提取点云,再到抓取姿态
算法
姜鱼问生28 分钟前
密码明明一样,为什么 GPG 说“错的“?
后端·算法·架构
启观川42 分钟前
数据结构与算法-第 3 章 常用算法-贪心算法
数据结构·笔记·python·算法·贪心算法
对空六课1 小时前
指标口径生效时间的版本查询实现
大数据·服务器·前端·算法·数据分析
对空六课1 小时前
RFM分层边界变化的回溯计算
大数据·服务器·前端·数据库·人工智能·算法·数据分析
一勺思维1 小时前
我为什么把 Agent 的核心逻辑从 LangChain 里搬出来手写
算法
水饺编程1 小时前
第2章:Linux 基础,clear 命令
linux·c语言·汇编
碧海银沙音频科技研究院1 小时前
基于炬芯ATS308X的LE aduio LC3编解码算法功能实现
算法
小蒋观天下1 小时前
厂区人员徘徊游荡判别——基于时序轨迹速度的逗留行为分级算法落地
大数据·人工智能·深度学习·算法·机器学习·ai大模型