Longest Harmonious Subsequence (Easy)
Input: [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].Basic Idea:
class Solution { public: int findLHS(vector<int>& nums) { unordered_map<int, int> _map; for (int num : nums) { ++_map[num]; } int res = 0; for (auto pair : _map) { if (_map.count(pair.first - 1)) { res = max(res, pair.second + _map[pair.first - 1]); } } return res; } };class Solution { public int findLHS(int[] nums) { Map<Integer, Integer> map = new HashMap<>(); for (int num : nums) map.put(num, map.getOrDefault(num, 0) + 1); int res = 0; for (Map.Entry<Integer, Integer> entry : map.entrySet()) { if (map.containsKey(entry.getKey() - 1)) { res = Math.max(res, entry.getValue() + map.get(entry.getKey() - 1)); } } return res; } }