Skip to content

Commit 3b0e996

Browse files
Sean PrashadSean Prashad
authored andcommitted
Update 904_Fruit_Into_Baskets.java
1 parent 9b8e709 commit 3b0e996

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

Sliding Window/904_Fruit_Into_Baskets.java

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,20 +4,22 @@ public int totalFruit(int[] tree) {
44
return 0;
55
}
66

7-
int start = 0, end = 0, result = 0;
87
Map<Integer, Integer> hm = new HashMap<>();
8+
int s = 0, e = 0, result = 0;
99

10-
while (end < tree.length) {
11-
hm.put(tree[end], end++);
10+
while (e < tree.length) {
11+
hm.put(tree[e], hm.getOrDefault(tree[e], 0) + 1);
12+
++e;
1213

13-
if (hm.size() > 2) {
14-
int minIdx = Collections.min(hm.values());
15-
start = minIdx + 1;
16-
17-
hm.remove(tree[minIdx]);
14+
while (hm.size() > 2) {
15+
hm.put(tree[s], hm.get(tree[s]) - 1);
16+
if (hm.get(tree[s]) == 0) {
17+
hm.remove(tree[s]);
18+
}
19+
++s;
1820
}
1921

20-
result = Math.max(result, end - start);
22+
result = Math.max(result, e - s);
2123
}
2224

2325
return result;

0 commit comments

Comments
 (0)