594. Longest Harmonious Subsequence

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int findLHS(int[] nums) {
Arrays.sort(nums);
int maxLength = 0;

int i = 0;
for (int j = 0; j < nums.length; j++) {
while (nums[j] - nums[i] > 1) {
i++;
}
if (nums[j] != nums[i]) {
maxLength = Math.max(maxLength, j - i + 1);
}
}

return maxLength;
}
}

References

594. Longest Harmonious Subsequence