Longest Harmonious Subsequence
Problem
We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1
.
Given an integer array nums
, return the length of its longest harmonious subsequence among all its possible subsequences.
A subsequence of 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.
Constraints
1 <= nums.length <= 2 * 104
-109 <= nums[i] <= 109
Solution
The problem Longest Harmonious Subsequence
can be solved by sorting the given array and finding the maximum length of consecutive elements with a value difference of 1.
Implementation
class Solution
{
public:
int findLHS(vector<int> &nums)
{
int ret = 0;
sort(nums.begin(), nums.end());
int left = 0, right = 0;
while (right < nums.size())
{
if (nums[left] + 1 < nums[right])
left += 1;
else
{
if (nums[left] + 1 == nums[right])
ret = max(ret, right - left + 1);
right += 1;
}
}
return ret;
}
};