Skip to content

Commit 70600a3

Browse files
authored
Update Longest Harmonious Subsequence.java
1 parent 9e2e258 commit 70600a3

File tree

1 file changed

+10
-7
lines changed

1 file changed

+10
-7
lines changed
Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,16 @@
11
class Solution {
22
public int findLHS(int[] nums) {
3-
Map<Integer, Long> map = Arrays.stream(nums).boxed()
4-
.collect(Collectors.groupingBy(Function.identity(), HashMap::new, Collectors.counting()));
5-
int result = 0;
6-
for (Integer key : map.keySet()) {
7-
if (map.containsKey(key + 1)) {
8-
result = Math.max(result, (int) (map.get(key) + map.get(key + 1)));
3+
int maxSubarraySize = 0;
4+
Map<Integer, Integer> map = new HashMap<>();
5+
for (int num : nums) {
6+
map.put(num, map.getOrDefault(num, 0) + 1);
7+
if (map.containsKey(num + 1)) {
8+
maxSubarraySize = Math.max(maxSubarraySize, map.get(num) + map.get(num + 1));
9+
}
10+
if (map.containsKey(num - 1)) {
11+
maxSubarraySize = Math.max(maxSubarraySize, map.get(num) + map.get(num - 1));
912
}
1013
}
11-
return result;
14+
return maxSubarraySize;
1215
}
1316
}

0 commit comments

Comments
 (0)