Skip to content

Commit 45d07c3

Browse files
authored
Merge pull request #3158 from a1exanddrovich/0904-dev
Create: 0904-fruit-into-baskets.java
2 parents 9485746 + 8d8b5c4 commit 45d07c3

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

java/0904-fruit-into-baskets.java

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
class Solution {
2+
public int totalFruit(int[] fruits) {
3+
Map<Integer, Integer> fruitTypeToItsCount = new HashMap<>();
4+
int maxTotalFruits = 0;
5+
int l = 0;
6+
int r = 0;
7+
8+
while (r < fruits.length) {
9+
fruitTypeToItsCount.put(fruits[r], fruitTypeToItsCount.getOrDefault(fruits[r], 0) + 1);
10+
11+
while (fruitTypeToItsCount.size() > 2) {
12+
fruitTypeToItsCount.put(fruits[l], fruitTypeToItsCount.get(fruits[l]) - 1);
13+
if (fruitTypeToItsCount.get(fruits[l]) == 0) {
14+
fruitTypeToItsCount.remove(fruits[l]);
15+
}
16+
l++;
17+
}
18+
19+
maxTotalFruits = Math.max(maxTotalFruits, r - l + 1);
20+
r++;
21+
}
22+
23+
return maxTotalFruits;
24+
}
25+
}

0 commit comments

Comments
 (0)