Longest Harmonious Subsequence in C++

Suppose we have an integer array; we have to find the length of its longest harmonious subsequence among all its possible subsequences. As we know a harmonious sequence array is an array where the difference between its maximum value and its minimum value is exactly 1.

So, if the input is like [1,3,2,2,5,2,3,7], then the output will be 5, as the longest harmonious subsequence is [4,3,3,3,4].

To solve this, we will follow these steps −

  • Define one map m

  • for n in nums −

    • (increase m[n] by 1)

  • for key-value pair (k,v) in m −

    • it := position of (k+1) in m

    • if 'it' is in m, then −

      • max_:= maximum of max_ and value of it

  • return max_


Let us see the following implementation to get a better understanding −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   int findLHS(vector<int>& nums) {
      unordered_map<int, int> m;
      for (const int n : nums)
      int max_{ 0 };
      for (const auto & [ k, v ] : m) {
         auto it = m.find(k + 1);
         if (it != m.end())
            max_ = max(max_, v + it->second);
      return max_;
   Solution ob;
   vector<int> v = {2,4,3,3,6,3,4,8};
   cout << (ob.findLHS(v));





Updated on: 11-Jun-2020


Kickstart Your Career

Get certified by completing the course

Get Started