Count every value, then combine each value's frequency with the frequency of its next integer. Checking only adjacent values avoids constructing subsequences.
Complexity
O(n) time and O(n) space, where n is the number of values.
Find the longest subsequence whose maximum and minimum differ by exactly one.
Count every value, then combine each value's frequency with the frequency of its next integer. Checking only adjacent values avoids constructing subsequences.
O(n) time and O(n) space, where n is the number of values.
package main
func findLHS(nums []int) int {
frequency := make(map[int]int, len(nums))
for _, value := range nums {
frequency[value]++
}
longest := 0
for value, count := range frequency {
if nextCount, ok := frequency[value+1]; ok && count+nextCount > longest {
longest = count + nextCount
}
}
return longest
}
from collections import Counter
class Solution:
def findLHS(self, nums: list[int]) -> int:
frequency = Counter(nums)
return max(
(count + frequency[value + 1] for value, count in frequency.items() if value + 1 in frequency),
default=0,
)
function findLHS(nums: number[]): number {
const frequency = new Map<number, number>();
for (const value of nums) frequency.set(value, (frequency.get(value) ?? 0) + 1);
let longest = 0;
for (const [value, count] of frequency) {
const nextCount = frequency.get(value + 1);
if (nextCount !== undefined) longest = Math.max(longest, count + nextCount);
}
return longest;
}