-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestHarmoniousSubseq.cpp
More file actions
40 lines (38 loc) · 985 Bytes
/
LongestHarmoniousSubseq.cpp
File metadata and controls
40 lines (38 loc) · 985 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>
#include<vector>
#include<map>
using namespace std;
// todo: 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.
int findLHS(vector<int>& nums)
{
map<int, int> m;
int mx = 0;
for(int i=0; i<nums.size(); i++)
{
m[nums[i]]++;
}
map<int, int>::iterator it;
map<int, int>::iterator next_it;
it = m.begin();
next_it = m.begin();
next_it++;
for(; next_it!=m.end(); it++, next_it++)
{
// cout << (it)->first << " " << (it)->first << endl;
if(it->first == next_it->first - 1)
{
int sum = it->second + next_it->second;
mx = max(sum, mx);
}
}
return mx;
}
int main()
{
vector<int> v = {1,4,3,1,2,3,2,3,3,2};
cout << findLHS(v);
}
// LC: Q.594