-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLongestHarmoniousSubsequence.java
More file actions
38 lines (27 loc) · 1.03 KB
/
LongestHarmoniousSubsequence.java
File metadata and controls
38 lines (27 loc) · 1.03 KB
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
class Solution {
public int findLHS(int[] nums) {
Arrays.sort(nums);
int result = 0;
int firstStart = 0;
int secondStart = 0;
for (int i = 1; i < nums.length; i++) {
if (nums[i] != nums[i-1]) {
if (nums[i] - nums[i-1] == 1) {
int firstSum = i - firstStart;
secondStart = i;
while (i < nums.length && nums[i] == nums[secondStart]) {
i++;
}
i--;
int secondSum = i - secondStart + 1;
int currentResult = firstSum + secondSum;
result = (result < currentResult) ? currentResult : result;
firstStart = secondStart;
} else {
firstStart = i;
}
}
}
return result;
}
}