
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)
1using System;
2using System.Collections.Generic;
3
4public class Solution {
5 public int FindLHS(int[] nums) {
6 Dictionary<int, int> countDictionary = new Dictionary<int, int>();
7 foreach (var num in nums) {
8 if (countDictionary.ContainsKey(num)) {
9 countDictionary[num]++;
10 } else {
11 countDictionary[num] = 1;
12 }
13 }
14 int maxLength = 0;
15 foreach (var key in countDictionary.Keys) {
16 if (countDictionary.ContainsKey(key + 1)) {
17 maxLength = Math.Max(maxLength, countDictionary[key] + countDictionary[key + 1]);
18 }
19 }
20 return maxLength;
21 }
22}C# uses a Dictionary to hold counts of numbers. The solution checks each key for the presence of its consecutive integer to potentially form a longer subsequence.
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.