Description
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 <= 1051 <= nums[i] <= 105
Solutions
Solution 1: Array or Hash Table
We use cnt to record the number of times each element v appears in nums, and ccnt to record the number of times each count appears. The maximum number of times an element appears is represented by mx.
While traversing nums:
- If the maximum count mx=1, it means that each number in the current prefix appears 1 time. If we delete any one of them, the remaining numbers will all have the same count.
- If all numbers appear mx and mx-1 times, and only one number appears mx times, then we can delete one occurrence of the number that appears mx times. The remaining numbers will all have a count of mx-1, which meets the condition.
- If, except for one number, all other numbers appear mx times, then we can delete the number that appears once. The remaining numbers will all have a count of mx, which meets the condition.
The time complexity is O(n), and the space complexity is O(n). Here, n is the length of the nums array.
class Solution: def maxEqualFreq(self, nums: List[int]) -> int: cnt = Counter() ccnt = Counter() ans = mx = 0 for i, v in enumerate(nums, 1): if v in cnt: ccnt[cnt[v]] -= 1 cnt[v] += 1 mx = max(mx, cnt[v]) ccnt[cnt[v]] += 1 if mx == 1: ans = i elif ccnt[mx] * mx + ccnt[mx - 1] * (mx - 1) == i and ccnt[mx] == 1: ans = i elif ccnt[mx] * mx + 1 == i and ccnt[1] == 1: ans = i return ans(code-box)
