Skip to content

Commit 83f3bd9

Browse files
authored
Create 594. Longest Harmonious Subsequence (#829)
2 parents b0ad97e + 35dd7a6 commit 83f3bd9

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

594. Longest Harmonious Subsequence

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
class Solution {
2+
public:
3+
int findLHS(vector<int>& nums) {
4+
// Count frequency of each number using hash map
5+
unordered_map<int, int> freq;
6+
for (int num : nums) {
7+
freq[num]++;
8+
}
9+
10+
int maxLength = 0;
11+
12+
// For each unique number, check if num+1 exists
13+
for (auto& pair : freq) {
14+
int currentNum = pair.first;
15+
int currentCount = pair.second;
16+
17+
// Check if currentNum + 1 exists in the map
18+
if (freq.find(currentNum + 1) != freq.end()) {
19+
// Calculate harmonious subsequence length using currentNum and currentNum+1
20+
int harmoniousLength = currentCount + freq[currentNum + 1];
21+
maxLength = max(maxLength, harmoniousLength);
22+
}
23+
}
24+
25+
return maxLength;
26+
}
27+
};

0 commit comments

Comments
 (0)