# 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 nums[4]=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
``````

Example 3:

``````Input: nums = [1,1,1,2,2,2]
Output: 5
``````

Example 4:

``````Input: nums = [10,2,8,9,3,8,1,5,2,3,7,6]
Output: 8
``````

Constraints:

• `2 <= nums.length <= 105`
• `1 <= nums[i] <= 105`

``````class Solution {
public:
int maxEqualFreq(vector<int>& nums) {
int res = 0, mx = 0, n = nums.size();
unordered_map<int, int> numCnt;
unordered_map<int, int> freq;
for (int i = 0; i < n; ++i) {
int num = nums[i], cnt = numCnt[num];
mx = max(mx, ++numCnt[num]);
if (freq[cnt] > 0) --freq[cnt];
++freq[cnt + 1];
if (mx * freq[mx] == i || (mx - 1) * (freq[mx - 1] + 1) == i || mx == 1) {
res = i + 1;
}
}
return res;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/1224

https://leetcode.com/problems/maximum-equal-frequency/

https://leetcode.com/problems/maximum-equal-frequency/discuss/403743/JavaC%2B%2BPython-Only-2-Cases%3A-Delete-it-or-not

https://leetcode.com/problems/maximum-equal-frequency/discuss/403628/Easy-Python-Solution-Concise-10-lines-Explained-O(N)

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation