Skip to content

1224. Maximum Equal Frequency 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
 public:
  int maxEqualFreq(vector<int>& nums) {
    int ans = 0;
    int maxFreq = 0;
    unordered_map<int, int> count;
    unordered_map<int, int> freq;

    for (int i = 0; i < nums.size(); ++i) {
      int num = nums[i];
      --freq[count[num]];
      ++count[num];
      ++freq[count[num]];
      maxFreq = max(maxFreq, count[num]);
      if (maxFreq == 1 || maxFreq * freq[maxFreq] == i ||
          (maxFreq - 1) * (freq[maxFreq - 1] + 1) == i)
        ans = i + 1;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution {
  public int maxEqualFreq(int[] nums) {
    int ans = 0;
    int maxFreq = 0;
    Map<Integer, Integer> count = new HashMap<>();
    Map<Integer, Integer> freq = new HashMap<>();

    for (int i = 0; i < nums.length; ++i) {
      int currentFreq = count.getOrDefault(nums[i], 0);
      freq.put(currentFreq, freq.getOrDefault(currentFreq, 0) - 1);
      int updatedFreq = currentFreq + 1;
      count.put(nums[i], updatedFreq);
      freq.put(updatedFreq, freq.getOrDefault(updatedFreq, 0) + 1);
      maxFreq = Math.max(maxFreq, updatedFreq);
      if (maxFreq == 1 || maxFreq * freq.get(maxFreq) == i ||
          (maxFreq - 1) * (freq.get(maxFreq - 1) + 1) == i)
        ans = i + 1;
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def maxEqualFreq(self, nums: List[int]) -> int:
    ans = 0
    maxFreq = 0
    count = Counter()
    freq = Counter()

    for i, num in enumerate(nums):
      freq[count[num]] -= 1
      count[num] += 1
      freq[count[num]] += 1
      maxFreq = max(maxFreq, count[num])
      if maxFreq == 1 or maxFreq * freq[maxFreq] == i or (maxFreq - 1) * (freq[maxFreq - 1] + 1) == i:
        ans = i + 1

    return ans