904. Fruit Into Baskets
Solution
public int totalFruit(int[] tree) {
int n = tree.length;
int[] counts = new int[n];
int start = 0, end = 0, typeCount = 0, ret = 0;
while(end < n){
int num = tree[end];
counts[num]++;
if(counts[num] == 1){
typeCount++;
}
while(typeCount > 2){
int startNum = tree[start];
counts[startNum]--;
if(counts[startNum] == 0){
typeCount--;
}
start++;
}
ret = Math.max(ret, end - start + 1);
end++;
}
return ret;
}
Last updated
Was this helpful?