Skip to content

Commit 759fd3a

Browse files
authored
Update Fruit Into Baskets.java
1 parent 69b93f9 commit 759fd3a

File tree

1 file changed

+15
-16
lines changed

1 file changed

+15
-16
lines changed

Medium/Fruit Into Baskets.java

Lines changed: 15 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
11
class Solution {
2-
public int totalFruit(int[] tree) {
2+
public int totalFruit(int[] fruits) {
33
Map<Integer, Integer> map = new HashMap<>();
4-
int maxCount = 0;
5-
int start = 0;
6-
int end = 0;
7-
int n = tree.length;
8-
while (end < n) {
9-
map.put(tree[end], map.getOrDefault(tree[end], 0) + 1);
10-
while (map.size() > 2) {
11-
map.put(tree[start], map.get(tree[start]) - 1);
12-
if (map.get(tree[start]) == 0) {
13-
map.remove(tree[start]);
4+
int startIdx = 0;
5+
int endIdx = 0;
6+
int n = fruits.length;
7+
int maxPickedCount = 0;
8+
while (endIdx < n) {
9+
map.put(fruits[endIdx], map.getOrDefault(fruits[endIdx++], 0) + 1);
10+
while (startIdx < endIdx && map.size() > 2) {
11+
map.put(fruits[startIdx], map.get(fruits[startIdx]) - 1);
12+
if (map.get(fruits[startIdx]) == 0) {
13+
map.remove(fruits[startIdx]);
1414
}
15-
start++;
15+
startIdx++;
1616
}
17-
end++;
18-
maxCount = Math.max(maxCount, end - start);
17+
maxPickedCount = Math.max(maxPickedCount, endIdx - startIdx);
1918
}
20-
return maxCount;
21-
}
19+
return maxPickedCount;
20+
}
2221
}

0 commit comments

Comments
 (0)