Longest Harmonious Subsequence Problem


Description

LeetCode Problem 594.

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.

Example 1:

1
2
3
Input: nums = [1,3,2,2,5,2,3,7]
Output: 5
Explanation: The longest harmonious subsequence is [3,2,2,2,3].

Example 2:

1
2
Input: nums = [1,2,3,4]
Output: 2

Example 3:

1
2
Input: nums = [1,1,1,1]
Output: 0

Constraints:

  • 1 <= nums.length <= 2 * 10^4
  • -10^9 <= nums[i] <= 10^9


Sample C++ Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
    int findLHS(vector<int>& nums) {
        unordered_map<int,int> m;
        int res = 0;
        for (auto i: nums) {
            m[i] ++;
            if (m.count(i+1))
                res = max(res, m[i] + m[i+1]);
            if (m.count(i-1))
                res = max(res, m[i] + m[i-1]);
        }
        return res;        
    }
};




Related Posts

Find Duplicate Subtrees Problem

LeetCode 652. Given the rootof a binary tree, return all...

Delete And Earn Problem

LeetCode 740. You are given an integer array nums. You...

Degree Of An Array Problem

LeetCode 697. Given a non-empty array of non-negative integers nums,...

Custom Sort String Problem

LeetCode 791. You are given two strings order and s....

Basic Calculator IV Problem

LeetCode 770. Given an expression such as expression = “e...

Sort Characters By Frequency Problem

LeetCode 451. Given a string s, sort it in decreasing...