
Sponsored
Sponsored
This approach leverages a map (or dictionary in Python) to count the frequency of each number in the array. Once we know the count of each number, we can iterate through the keys and check for pairs of consecutive numbers (n and n+1). The length of a harmonious subsequence that can be formed is the sum of the counts of these consecutive numbers.
Time Complexity: O(n), Space Complexity: O(n)
1from collections import Counter
2
3def findLHS(nums):
4 count = Counter(nums)
5 max_length = 0
6 for num in count:
7 if num + 1 in count:
8 max_length = max(max_length, count[num] + count[num + 1])
9 return max_lengthUsing Python's Counter from the collections module, the frequency of each number is counted. We then iterate through the counted numbers to find pairs of consecutive numbers.
An alternative approach would be to sort the numbers. After sorting, we can use a two-pointer technique to find the longest subsequence where the difference between the smallest and largest value is exactly one. This method may be less efficient due to the sorting step but provides a straightforward solution.
Time Complexity: O(n log n) due to sorting, Space Complexity: O(1) if counting sort or constant space partition approach is used.
1
public class Solution {
public int FindLHS(int[] nums) {
Array.Sort(nums);
int left = 0, maxLength = 0;
for (int right = 1; right < nums.Length; right++) {
while (nums[right] - nums[left] > 1) {
left++;
}
if (nums[right] - nums[left] == 1) {
maxLength = Math.Max(maxLength, right - left + 1);
}
}
return maxLength;
}
}In C#, sorting the array is followed by a two-pointer run over the sorted list to calculate potential subsequence lengths.