Skip to content

Latest commit

 

History

History

1224

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

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

Companies:
American Express

Related Topics:
Array, Hash Table

Solution 1. Frequency Map

// OJ: https://leetcode.com/problems/maximum-equal-frequency/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(N)
class Solution {
public:
    int maxEqualFreq(vector<int>& A) {
        unordered_map<int, int> cnt;
        map<int, int> freq;
        int N = A.size(), ans = 0;
        for (int i = 0; i < N; ++i) {
            int c = ++cnt[A[i]];
            if (c - 1 > 0) {
                if (--freq[c - 1] == 0) freq.erase(c - 1);
            }
            ++freq[c];
            if (freq.size() == 2) {
                auto &[a, ca] = *freq.begin();
                auto &[b, cb] = *freq.rbegin();
                if ((b == a + 1 && cb == 1) || (a == 1 && ca == 1)) ans = i + 1;
            } else if (freq.size() == 1) {
                auto &[a, ca] = *freq.begin();
                if (a == 1 || ca == 1) ans = i + 1;
            }
        }
        return ans;
    }
};