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

<p>If after removing one element there are no remaining elements, it&#39;s still considered that every appeared number has the same number of ocurrences (0).</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> nums = [2,2,1,1,5,3,3,5]
<strong>Output:</strong> 7
<strong>Explanation:</strong> 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.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> nums = [1,1,1,2,2,2,3,3,3,4,4,4,5]
<strong>Output:</strong> 13
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>2 &lt;= nums.length &lt;= 10<sup>5</sup></code></li>
	<li><code>1 &lt;= nums[i] &lt;= 10<sup>5</sup></code></li>
</ul>

class Solution:
    def maxEqualFreq(self, nums: List[int]) -> int:
        max_len = 0
        nums_freqs, freqs_counts = dict(), dict()

        for idx, num in enumerate(nums):
            if num not in nums_freqs.keys():
                nums_freqs.update({num: 0})
            nums_freqs[num] += 1

            current_freq = nums_freqs[num]
            if current_freq not in freqs_counts.keys():
                freqs_counts.update({current_freq: 0})
            freqs_counts[current_freq] += 1

            if current_freq > 1:  # Need to update old frequency's count.
                freqs_counts[current_freq - 1] -= 1
                if freqs_counts[current_freq - 1] == 0:
                    del freqs_counts[current_freq - 1]
            
            if len(freqs_counts) == 1:
                # Each number occurs once, or a number occurs every time.
                if 1 in freqs_counts.keys() or 1 in freqs_counts.values():
                    max_len = idx + 1

            if len(freqs_counts) == 2:
                # A number occurs once while others has the same frequency.
                if 1 in freqs_counts.keys() and freqs_counts[1] == 1:
                    max_len = idx + 1
                    continue
                
                max_freq, min_freq = max(freqs_counts.keys()), min(freqs_counts.keys())
                # Higher frequency can merge into lower freqeuency.
                if freqs_counts[max_freq] == 1 and max_freq - min_freq == 1:
                    max_len = idx + 1
                    
        return max_len

23600