File tree Expand file tree Collapse file tree 1 file changed +15
-16
lines changed Expand file tree Collapse file tree 1 file changed +15
-16
lines changed Original file line number Diff line number Diff line change 1
1
class Solution {
2
- public int totalFruit (int [] tree ) {
2
+ public int totalFruit (int [] fruits ) {
3
3
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 ]);
14
14
}
15
- start ++;
15
+ startIdx ++;
16
16
}
17
- end ++;
18
- maxCount = Math .max (maxCount , end - start );
17
+ maxPickedCount = Math .max (maxPickedCount , endIdx - startIdx );
19
18
}
20
- return maxCount ;
21
- }
19
+ return maxPickedCount ;
20
+ }
22
21
}
You can’t perform that action at this time.
0 commit comments