Skip to content

Commit 677a2f5

Browse files
authored
Added task 594.
1 parent cc565d7 commit 677a2f5

File tree

3 files changed

+89
-0
lines changed

3 files changed

+89
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
package g0501_0600.s0594_longest_harmonious_subsequence;
2+
3+
// #Easy #Array #Hash_Table #Sorting
4+
5+
import java.util.Arrays;
6+
7+
public class Solution {
8+
public int findLHS(int[] nums) {
9+
Arrays.sort(nums);
10+
int max = 0;
11+
int lastN = 0;
12+
int curN = 1;
13+
int cur = nums[0];
14+
for (int i = 1; i < nums.length; i++) {
15+
if (nums[i] > cur) {
16+
if (lastN > 0 && curN > 0 && lastN + curN > max) {
17+
max = lastN + curN;
18+
}
19+
// if diff more than 1, don't count
20+
lastN = nums[i] - cur == 1 ? curN : 0;
21+
curN = 1;
22+
cur = nums[i];
23+
} else {
24+
curN++;
25+
}
26+
}
27+
if (lastN > 0 && curN > 0 && lastN + curN > max) {
28+
max = lastN + curN;
29+
}
30+
return max;
31+
}
32+
}
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
594\. Longest Harmonious Subsequence
2+
3+
Easy
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+
13+
**Input:** nums = [1,3,2,2,5,2,3,7]
14+
15+
**Output:** 5
16+
17+
**Explanation:** The longest harmonious subsequence is [3,2,2,2,3].
18+
19+
**Example 2:**
20+
21+
**Input:** nums = [1,2,3,4]
22+
23+
**Output:** 2
24+
25+
**Example 3:**
26+
27+
**Input:** nums = [1,1,1,1]
28+
29+
**Output:** 0
30+
31+
**Constraints:**
32+
33+
* <code>1 <= nums.length <= 2 * 10<sup>4</sup></code>
34+
* <code>-10<sup>9</sup> <= nums[i] <= 10<sup>9</sup></code>
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package g0501_0600.s0594_longest_harmonious_subsequence;
2+
3+
import static org.hamcrest.CoreMatchers.equalTo;
4+
import static org.hamcrest.MatcherAssert.assertThat;
5+
6+
import org.junit.jupiter.api.Test;
7+
8+
class SolutionTest {
9+
@Test
10+
void findLHS() {
11+
assertThat(new Solution().findLHS(new int[] {1, 3, 2, 2, 5, 2, 3, 7}), equalTo(5));
12+
}
13+
14+
@Test
15+
void findLHS2() {
16+
assertThat(new Solution().findLHS(new int[] {1, 2, 3, 4}), equalTo(2));
17+
}
18+
19+
@Test
20+
void findLHS3() {
21+
assertThat(new Solution().findLHS(new int[] {1, 1, 1, 1}), equalTo(0));
22+
}
23+
}

0 commit comments

Comments
 (0)