-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
33 lines (24 loc) · 955 Bytes
/
Solution.java
File metadata and controls
33 lines (24 loc) · 955 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
class Solution {
public int totalFruit(int[] fruits) {
int n = fruits.length;
int windowStart = 0;
Map<Integer,Integer> fruitTypeToNumMap = new HashMap<>();
int maxLength = Integer.MIN_VALUE;
for(int windowEnd=0; windowEnd<n;windowEnd++){
fruitTypeToNumMap.put(fruits[windowEnd],fruitTypeToNumMap.getOrDefault(fruits[windowEnd],0)+1);
while(fruitTypeToNumMap.size()>2){
fruitTypeToNumMap.put(fruits[windowStart], fruitTypeToNumMap.get(fruits[windowStart])-1);
if(fruitTypeToNumMap.get(fruits[windowStart])==0){
fruitTypeToNumMap.remove(fruits[windowStart]);
}
windowStart++;
}
maxLength = Math.max(maxLength, windowEnd-windowStart+1);
}
return maxLength;
}
}