algorithm

594. Longest Harmonious Subsequence

식피두 2020. 8. 31. 00:26

https://leetcode.com/problems/longest-harmonious-subsequence/

 

Longest Harmonious Subsequence - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

450ms

import collections

class Solution:
    def findLHS(self, nums: List[int]) -> int:
        if len(nums) < 1:
            return 0
        if len(set(nums)) == 1:
            return 0
        
        uniq_nums = set(nums)
        memo = collections.defaultdict(int)
        
        res = 0
        for idx, num in enumerate(nums):
            if num-1 in uniq_nums:
                _key = '{}-{}'.format(num-1, num)
                memo[_key] += 1
                res = max(res, memo[_key])
            if num+1 in uniq_nums:
                _key = '{}-{}'.format(num, num+1)
                memo[_key] += 1
                res = max(res, memo[_key])
            
        return res

 

simplify

 

300ms

class Solution:
    def findLHS(self, A):
        count = collections.Counter(A)
        ans = 0
        for x in count:
            if x+1 in count:
                ans = max(ans, count[x] + count[x+1])
        return ans

'algorithm' 카테고리의 다른 글

676. Implement Magic Dictionary  (0) 2020.09.03
662. Maximum Width of Binary Tree  (0) 2020.08.31
654. Maximum Binary Tree  (0) 2020.08.31
696. Count Binary Substrings  (0) 2020.08.31
599. Minimum Index Sum of Two Lists  (0) 2020.08.31