
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)
1var findLHS = function(nums) {
2 let countMap = new Map();
3 for (let num of nums) {
4 countMap.set(num, (countMap.get(num) || 0) + 1);
5 }
6 let maxLength = 0;
7 for (let [key, value] of countMap.entries()) {
8 if (countMap.has(key + 1)) {
9 maxLength = Math.max(maxLength, value + countMap.get(key + 1));
10 }
11 }
12 return maxLength;
13};JavaScript's solution involves using a Map to keep track of each number's occurrences. We then check if a consecutive integer is present in the Map for each key.
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#include <algorithm>
using namespace std;
int findLHS(vector<int>& nums) {
sort(nums.begin(), nums.end());
int left = 0, maxLength = 0;
for (int right = 1; right < nums.size(); ++right) {
while (nums[right] - nums[left] > 1) {
++left;
}
if (nums[right] - nums[left] == 1) {
maxLength = max(maxLength, right - left + 1);
}
}
return maxLength;
}This C++ solution sorts the input and then applies the two-pointer approach to calculate the longest harmonious subsequence of consecutive elements.