A harmonic subsequence consists of only two numbers x and x+1. We can count the frequency of each number using a hash map and then find the maximum count(x) + count(x+1).
- Count frequencies of all numbers in
numsusingCounter. max_len = 0.- For each
xin the counter:- If
x + 1is also in the counter:max_len = max(max_len, count[x] + count[x+1]).
- If
- Return
max_len.
- Time Complexity: O(N).
- Space Complexity: O(N).
from collections import Counter
def find_lhs(nums):
counts = Counter(nums)
max_len = 0
for x in counts:
if x + 1 in counts:
max_len = max(max_len, counts[x] + counts[x + 1])
return max_len