1. 程式人生 > >算法(69)----最長和諧子序列

算法(69)----最長和諧子序列

之間 int 序列 ons ron class code turn 長度

一、題目:最長和諧子序列:

和諧數組是指一個數組裏元素的最大值和最小值之間的差別正好是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)----最長和諧子序列