Leetcode 594. Longest Harmonious Subsequence
Given an integer array nums
, return the length of the longest harmonious subsequence among all its possible subsequences.
A harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
This algorithm ensures that we only need to traverse the array a couple of times, making it efficient.
import java.util.HashMap;
import java.util.Map;
public class LongestHarmoniousSubsequence {
public int findLHS(int[] nums) {
Map<Integer, Integer> frequencyMap = new HashMap<>();
// Populate the frequency map
for (int num : nums) {
frequencyMap.put(num, frequencyMap.getOrDefault(num, 0) + 1);
}
int maxLength = 0;
// Iterate through the map to find the longest harmonious subsequence length
for (int key : frequencyMap.keySet()) {
if (frequencyMap.containsKey(key + 1)) {
int currentLength = frequencyMap.get(key) + frequencyMap.get(key + 1);
maxLength = Math.max(maxLength, currentLength);
}
}
return maxLength;
}
public static void main(String[] args) {
LongestHarmoniousSubsequence solution = new LongestHarmoniousSubsequence();
int[] nums = {1, 3, 2, 2, 5, 2, 3, 7};
System.out.println(solution.findLHS(nums)); // Output: 5
}
}
This code should solve the problem of finding the longest harmonious subsequence in a given array of integers by leveraging a hashmap to store frequencies and then checking adjacent keys to compute possible subsequences’ lengths.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?