Algorithm


Problem Name: 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

 

Constraints:

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

Code Examples

#1 Code Example with Javascript Programming

Code - Javascript Programming


const maxEqualFreq = function (nums) {
  const freqCnt = {}, cnt = {}, { max } = Math

  let res = 0, maxF = 0, i = 0
  for(const e of nums) {
    if(cnt[e] == null) cnt[e] = 0
    cnt[e]++

    const f = cnt[e]

    if(freqCnt[f - 1] == null) freqCnt[f - 1] = 0
    if(freqCnt[f] == null) freqCnt[f] = 0
    
    if(freqCnt[f - 1] > 0) freqCnt[f - 1]--
    freqCnt[f]++

    maxF = max(maxF, f)

    if(
      maxF === 1 ||
      maxF * freqCnt[maxF] === i ||
      (maxF - 1) * (freqCnt[maxF - 1] + 1) === i
    ) {
      res = i + 1
    }

    i++
  }

  return res
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [2,2,1,1,5,3,3,5]

Output

x
+
cmd
7

#2 Code Example with Python Programming

Code - Python Programming


class Solution:
    def maxEqualFreq(self, nums: List[int]) -> int:
        def okay():
            if len(dic) == 1 and (1 in dic or 1 in dic.values()):
                return True 
            if len(dic) == 2:
                c1, c2 = sorted(dic.keys())
                if c2 - c1 == 1 and dic[c2] == 1 or (c1 == 1 and dic[1] == 1):
                    return True
        cnt = collections.Counter(nums)
        dic = collections.Counter(cnt.values())
        l = len(nums)
        for num in nums[::-1]:
            if okay():
                return l
            dic[cnt[num]] -= 1
            if not dic[cnt[num]]:
                dic.pop(cnt[num])
            cnt[num] -= 1
            if cnt[num]:
                dic[cnt[num]] += 1
            l -= 1
            if okay():
                return l
Copy The Code & Try With Live Editor

Input

x
+
cmd
nums = [2,2,1,1,5,3,3,5]

Output

x
+
cmd
7
Advertisements

Demonstration


Previous
#1223 Leetcode Dice Roll Simulation Solution in C, C++, Java, JavaScript, Python, C# Leetcode
Next
#1227 Leetcode Airplane Seat Assignment Probability Solution in C, C++, Java, JavaScript, Python, C# Leetcode