Leetcode 594. Longest Harmonious Subsequence
Given an integer array nums
, return the length of its longest harmonious subsequence among all its possible subsequences.
A harmonious array is an array where the difference between its maximum value and its minimum value is exactly 1
.
A subsequence of an array is a sequence that can be derived from the array by deleting some or no elements without changing the order of the remaining elements.
Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
Input: nums = [1,2,3,4]
Output: 2
Explanation: The longest harmonious subsequence is [1,2] or [2,3] or [3,4].
Input: nums = [1,1,1,1]
Output: 0
Explanation: There is no harmonious subsequence since all elements are the same.
nums
) can be up to (10^4).nums[i]
) is in the range of ([-10^4, 10^4]).#include <vector>
#include <unordered_map>
using namespace std;
class Solution {
public:
int findLHS(vector<int>& nums) {
unordered_map<int, int> frequency;
// Count the frequency of each element
for (int num : nums) {
frequency[num]++;
}
int maxLength = 0;
// Check each key in the map
for (auto& entry : frequency) {
int num = entry.first;
if (frequency.find(num + 1) != frequency.end()) {
// Potential harmonious subsequence length
int currentLength = frequency[num] + frequency[num + 1];
maxLength = max(maxLength, currentLength);
}
}
return maxLength;
}
};
nums
.This solution is efficient given the constraints and ensures we check all potential harmonious subsequences in linear time.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?