码迷,mamicode.com
首页 > 编程语言 > 详细

算法(69)----最长和谐子序列

时间:2019-01-16 11:57:47      阅读:229      评论:0      收藏:0      [点我收藏+]

标签:cti   整数   bsp   obj   需要   str   from   原因   个数   

一、题目:最长和谐子序列:

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

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

示例 1:

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

 

二、代码:

from collections import Counter
class Solution(object):
    def findLHS(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        if not nums:
            return 0
        count = Counter(nums)
        res = 0
        for num in nums:
            if num+1 in count:
                res = max(res,count[num]+count[num+1])
        return res

 

算法(69)----最长和谐子序列

标签:cti   整数   bsp   obj   需要   str   from   原因   个数   

原文地址:https://www.cnblogs.com/Lee-yl/p/10269794.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!