
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
In Java, the solution begins with sorting the array, then uses two pointers to measure the longest subsequence found with adjacent integers.