1224. Maximum Equal Frequency

88 篇文章 0 订阅

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 <= 10^5
  • 1 <= nums[i] <= 10^5

思路:思路参考 https://leetcode.com/problems/maximum-equal-frequency/discuss/403743/JavaC%2B%2BPython-Only-2-Cases%3A-Delete-it-or-not

from collections import Counter
class Solution(object):
    def maxEqualFreq(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        count = Counter()
        freq = [0 for _ in range(len(nums)+1)]
        res = 0
        for idx,n in enumerate(nums):
            freq[count[n]] -= 1
            freq[count[n]+1] += 1
            count[n] += 1
            c = count[n]
            
            # 当前正好
            if freq[c]*c==idx+1:
                if idx+1<len(nums):
                    res = idx+2
            
            # 有一个多,把这个多的删除掉
            d = idx+1-freq[c]*c
            if freq[d]==1 and (d==c+1 or d==1):
                res = idx+1
            
        return res
        
s=Solution()
print(s.maxEqualFreq([2,2,1,1,5,3,3,5]))
print(s.maxEqualFreq([1,1,1,2,2,2,3,3,3,4,4,4,5]))
print(s.maxEqualFreq([1,1,1,2,2,2]))
print(s.maxEqualFreq([10,2,8,9,3,8,1,5,2,3,7,6]))
        

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值