Longest Harmonious Subsequence

Problem

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.

Analysis

The brute force approach would involve taking every possible combination. That would be horribly slow at time complexity of O(2^N).

Accepted

We use a map to store {item, item_count}. Then we iterate through the keys and look for key+1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<int, int> counts_map;

for (auto e: nums) {
counts_map[e]++;
}
int max_len = 0;
for(auto it = counts_map.cbegin(); it != counts_map.cend(); it++) {
if (counts_map.find(it->first + 1) != counts_map.cend()) {
max_len = max(max_len, counts_map[it->first] + counts_map[it->first + 1]);
}
}

return max_len;
}
};