You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented by an integer array fruits where fruits[i] is the type of fruit the ith tree produces.
You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
You only have two baskets, and each basket can only hold a single type of fruit. There is no limit on the amount of fruit each basket can hold.
Starting from any tree of your choice, you must pick exactly one fruit from every tree (including the start tree) while moving to the right. The picked fruits must fit in one of your baskets.
Once you reach a tree with fruit that cannot fit in your baskets, you must stop.
Given the integer array fruits, return the maximum number of fruits you can pick.
Input:
fruits = [1,2,1]
Output:
3
Explanation: We can pick from all 3 trees.
Example 2:
1
2
3
4
5
6
Input:
fruits = [0,1,2,2]
Output:
3
Explanation: We can pick from trees [1,2,2].
If we had started at the first tree, we would only pick from trees [0,1].
Example 3:
1
2
3
4
5
6
Input:
fruits = [1,2,3,2,2]
Output:
4
Explanation: We can pick from trees [2,3,2,2].
If we had started at the first tree, we would only pick from trees [1,2].
We want the longest subarray with at most two types of fruits. This is a classic sliding window problem where we expand the window to include new fruits and shrink it from the left when we have more than two types.
classSolution {
public:int totalFruit(vector<int>& fruits) {
unordered_map<int, int> cnt;
int ans =0, left =0;
for (int right =0; right < fruits.size(); ++right) {
cnt[fruits[right]]++;
while (cnt.size() >2) {
cnt[fruits[left]]--;
if (cnt[fruits[left]] ==0) cnt.erase(fruits[left]);
left++;
}
ans = max(ans, right - left +1);
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
functotalFruit(fruits []int) int {
cnt:=map[int]int{}
ans, left:=0, 0forright, f:=rangefruits {
cnt[f]++for len(cnt) > 2 {
cnt[fruits[left]]--ifcnt[fruits[left]] ==0 {
delete(cnt, fruits[left])
}
left++ }
ifright-left+1 > ans {
ans = right-left+1 }
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution {
publicinttotalFruit(int[] fruits) {
Map<Integer, Integer> cnt =new HashMap<>();
int ans = 0, left = 0;
for (int right = 0; right < fruits.length; right++) {
cnt.put(fruits[right], cnt.getOrDefault(fruits[right], 0) + 1);
while (cnt.size() > 2) {
cnt.put(fruits[left], cnt.get(fruits[left]) - 1);
if (cnt.get(fruits[left]) == 0) cnt.remove(fruits[left]);
left++;
}
ans = Math.max(ans, right - left + 1);
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
classSolution {
funtotalFruit(fruits: IntArray): Int {
val cnt = mutableMapOf<Int, Int>()
var ans = 0var left = 0for (right in fruits.indices) {
cnt[fruits[right]] = cnt.getOrDefault(fruits[right], 0) + 1while (cnt.size > 2) {
cnt[fruits[left]] = cnt[fruits[left]]!! - 1if (cnt[fruits[left]] ==0) cnt.remove(fruits[left])
left++ }
ans = maxOf(ans, right - left + 1)
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution:
deftotalFruit(self, fruits: list[int]) -> int:
from collections import defaultdict
cnt = defaultdict(int)
ans = left =0for right, f in enumerate(fruits):
cnt[f] +=1while len(cnt) >2:
cnt[fruits[left]] -=1if cnt[fruits[left]] ==0:
del cnt[fruits[left]]
left +=1 ans = max(ans, right - left +1)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
use std::collections::HashMap;
impl Solution {
pubfntotal_fruit(fruits: Vec<i32>) -> i32 {
letmut cnt = HashMap::new();
let (mut ans, mut left) = (0, 0);
for (right, &f) in fruits.iter().enumerate() {
*cnt.entry(f).or_insert(0) +=1;
while cnt.len() >2 {
let l = fruits[left];
*cnt.get_mut(&l).unwrap() -=1;
if cnt[&l] ==0 { cnt.remove(&l); }
left +=1;
}
ans = ans.max(right - left +1);
}
ans asi32 }
}
Instead of a hashmap, we can track the last two types and their most recent positions. This can be more space-efficient and sometimes faster in practice.
classSolution:
deftotalFruit(self, fruits: list[int]) -> int:
ans = left =0 type1 = type2 = last1 = last2 =-1for right, f in enumerate(fruits):
if f == type1 or f == type2:
passelse:
left = min(last1, last2) +1if f == type1:
last1 = right
elif f == type2:
last2 = right
elif last1 < last2:
type1 = f
last1 = right
else:
type2 = f
last2 = right
ans = max(ans, right - left +1)
return ans