
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)
1import java.util.HashMap;
2
3public class Solution {
4 public int findLHS(int[] nums) {
5 HashMap<Integer, Integer> countMap = new HashMap<>();
6 for(int num : nums) {
7 countMap.put(num, countMap.getOrDefault(num, 0) + 1);
8 }
9 int maxLength = 0;
10 for(int key : countMap.keySet()) {
11 if(countMap.containsKey(key + 1)) {
12 maxLength = Math.max(maxLength, countMap.get(key) + countMap.get(key + 1));
13 }
14 }
15 return maxLength;
16 }
17}The Java solution uses a HashMap to store the counts of each element, and for each key, it checks if the next consecutive key exists and calculates the potential longest harmonious 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
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.