
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)
1#include <vector>
2#include <unordered_map>
3
4using namespace std;
5
6int findLHS(vector<int>& nums) {
7 unordered_map<int, int> numCount;
8 for(auto num : nums) {
9 numCount[num]++;
10 }
11 int maxLength = 0;
12 for(auto& pair : numCount) {
13 if(numCount.find(pair.first + 1) != numCount.end()) {
14 maxLength = max(maxLength, pair.second + numCount[pair.first + 1]);
15 }
16 }
17 return maxLength;
18}In this C++ solution, an unordered map is used to track the frequency of occurrence of each number. We then check each key for its consecutive counterpart, adjust the maximum length conditionally.
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
The C implementation uses the qsort function to first sort the array, and then applies a two-pointer technique to find the longest subsequence with the desired difference of one.