same idea:(but as discussed above, no need to check e+1 and e -1 simultaneously, one is enoug.)

public int findLHS(int[] nums) { int ret = 0, sum; HashMap<Integer, Integer> hm = new HashMap<>(); for (int e : nums) hm.put(e, hm.getOrDefault(e, 0) + 1); for (int e : hm.keySet()) { sum = Math.max(hm.getOrDefault(e + 1, 0), hm.getOrDefault(e - 1, 0)) + hm.get(e); if (sum > ret && Math.max(hm.getOrDefault(e + 1, 0), hm.getOrDefault(e - 1, 0)) != 0) { ret = sum; } } return ret; }Longest Harmonious Subsequence