Fruit Into Baskets LeetCode solution in Java

1
class Solution {
2
public int totalFruit(int[] fruits) {
3
if (fruits == null || fruits.length == 0) {
4
return 0;
5
}
6
int start = 0, end = 0, res = 0;
7
HashMap<Integer, Integer> map =
8
new HashMap<>(); // key = type of fruit on tree, value = last index / newest index of that
9
// fruit
10

11
while (end < fruits.length) {
12
if (map.size() <= 2) {
13
map.put(fruits[end], end);
14
end++;
15
}
16

17
if (map.size() > 2) {
18
int leftMost = fruits.length;
19
for (int num : map.values()) {
20
leftMost = Math.min(leftMost, num);
21
}
22
map.remove(fruits[leftMost]);
23
start = leftMost + 1;
24
}
25

26
res = Math.max(res, end - start);
27
}
28
return res;
29
}
30
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0