https://leetcode.com/problems/longest-harmonious-subsequence/
- Hash Table
Count frequencies, then for each number check if num+1 exists; max pair length is answer.
O(n)
O(n)
import java.util.*;
class Solution {
public int findLHS(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
for (int n : nums) map.put(n, map.getOrDefault(n, 0) + 1);
int ans = 0;
for (int key : map.keySet()) {
if (map.containsKey(key + 1)) {
ans = Math.max(ans, map.get(key) + map.get(key+1));
}
}
return ans;
}
}