和谐数组是指一个数组里元素的最大值和最小值之间的差别正好是1。

现在,给定一个整数数组,你需要在所有可能的子序列中找到最长的和谐子序列的长度。

示例 1:

输入: [1,3,2,2,5,2,3,7]
输出: 5
原因: 最长的和谐数组是:[3,2,2,2,3].

说明: 输入的数组长度最大不超过20,000.

 

from collections import Counter
class Solution:
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        new_nums=Counter(nums)
        tmp = 0
        lastkey,lastvalue=None,None
        for key,value in sorted(new_nums.items()):
            if lastkey is not None and lastkey +1 ==key:
                tmp = max(tmp,value+lastvalue)
            lastkey,lastvalue=key,value
        return tmp

 

相关文章:

  • 2021-06-13
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-07
  • 2021-04-10
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-07-03
  • 2019-12-24
  • 2022-12-23
  • 2022-01-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案