594. Longest Harmonious Subsequence
We define a harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1.
Now, given an integer array, you need to find the length of its longest harmonious subsequence among all its possible subsequences.
Example 1:
Input: [1,3,2,2,5,2,3,7] Output: 5 Explanation: The longest harmonious subsequence is [3,2,2,2,3].
Note: The length of the input array will not exceed 20,000.
Solution: line12, to access the pair in map,p.first & p.second represent the key and value in the pair. use map[key] to access the corresponding value
1 class Solution { 2 public: 3 int findLHS(vector<int>& nums) { 4 if (!nums.size()) return 0; 5 int res=0; 6 map<int,int> m; 7 for (int num:nums){ 8 m[num]++; 9 } 10 int lastNum=0; 11 int lastFreq=0; 12 for (pair<int,int> p:m){ 13 int length=0; 14 if (lastFreq && p.first-lastNum==1){ 15 length=p.second+lastFreq; 16 } 17 res=max(res,length); 18 lastNum=p.first; 19 lastFreq=p.second; 20 } 21 return res; 22 } 23 };