Longest Harmonious Subsequence
Thoughts
Code
class Solution {
public int findLHS(int[] nums) {
Map<Integer, Integer> freq = new HashMap<>();
for (int i = 0; i < nums.length; i++) {
freq.put(nums[i], freq.getOrDefault(nums[i], 0) + 1);
}
int max = 0;
for (Integer num : freq.keySet()) {
if (freq.containsKey(num + 1)) {
max = Math.max(max, freq.get(num) + freq.get(num + 1));
}
}
return max;
}
}Analysis
Last updated