Skip to content

Commit 97d29b4

Browse files
committed
day 4
1 parent 58593a9 commit 97d29b4

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
/*
2+
Longest Harmonious Subsequence
3+
==============================
4+
5+
We define a harmonious array as an array where the difference between its maximum value and its minimum value is exactly 1.
6+
7+
Given an integer array nums, return the length of its longest harmonious subsequence among all its possible subsequences.
8+
9+
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.
10+
11+
Example 1:
12+
Input: nums = [1,3,2,2,5,2,3,7]
13+
Output: 5
14+
Explanation: The longest harmonious subsequence is [3,2,2,2,3].
15+
16+
Example 2:
17+
Input: nums = [1,2,3,4]
18+
Output: 2
19+
20+
Example 3:
21+
Input: nums = [1,1,1,1]
22+
Output: 0
23+
24+
Constraints:
25+
1 <= nums.length <= 2 * 104
26+
-109 <= nums[i] <= 109
27+
*/
28+
29+
class Solution
30+
{
31+
public:
32+
int findLHS(vector<int> &nums)
33+
{
34+
sort(nums.begin(), nums.end());
35+
int ans = 0;
36+
int i = 0, j = 0;
37+
while (i < nums.size() && j < nums.size())
38+
{
39+
while (j < nums.size() && (nums[j] == nums[i] || nums[j] == nums[i] + 1))
40+
j++;
41+
if (i != j && nums[i] == nums[j - 1])
42+
i++;
43+
else
44+
{
45+
ans = max(ans, j - i);
46+
i++;
47+
}
48+
j = i;
49+
}
50+
return ans == 1 ? 0 : ans;
51+
}
52+
};

Diff for: Leetcode Daily Challenge/February-2021/README.MD

+2-1
Original file line numberDiff line numberDiff line change
@@ -4,4 +4,5 @@
44
| :-: | :------------- | :-------: |
55
| 1. | [Number of 1 Bits](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3625/) | [cpp](./01.%20Number%20of%201%20Bits.cpp) |
66
| 2. | []() | [cpp](./02.%20.cpp) |
7-
| 3. | [Linked List Cycle](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3627/) | [cpp](./03.%20Linked%20List%20Cycle.cpp) |
7+
| 3. | [Linked List Cycle](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3627/) | [cpp](./03.%20Linked%20List%20Cycle.cpp) |
8+
| 4. | [Longest Harmonious Subsequence](https://leetcode.com/explore/challenge/card/february-leetcoding-challenge-2021/584/week-1-february-1st-february-7th/3628/) | [cpp](./04.%20Longest%20Harmonious%20Subsequence.cpp) |

0 commit comments

Comments
 (0)