We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
2 parents b0ad97e + 35dd7a6 commit 83f3bd9Copy full SHA for 83f3bd9
594. Longest Harmonious Subsequence
@@ -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