0904. 水果成篮【中等】
1. 📝 题目描述
你正在探访一家农场,农场从左到右种植了一排果树。这些树用一个整数数组 fruits 表示,其中 fruits[i] 是第 i 棵树上的水果 种类。
你想要尽可能多地收集水果。然而,农场的主人设定了一些严格的规矩,你必须按照要求采摘水果:
- 你只有 两个 篮子,并且每个篮子只能装 单一类型 的水果。每个篮子能够装的水果总量没有限制。
- 你可以选择任意一棵树开始采摘,你必须从 每棵 树(包括开始采摘的树)上 恰好摘一个水果。采摘的水果应当符合篮子中的水果类型。每采摘一次,你将会向右移动到下一棵树,并继续采摘。
- 一旦你走到某棵树前,但水果不符合篮子的水果类型,那么就必须停止采摘。
给你一个整数数组 fruits,返回你可以收集的水果的 最大 数目。
示例 1:
txt
输入:fruits = [1,2,1]
输出:3
解释:可以采摘全部 3 棵树。1
2
3
2
3
示例 2:
txt
输入:fruits = [0,1,2,2]
输出:3
解释:可以采摘 [1,2,2] 这三棵树。
如果从第一棵树开始采摘,则只能采摘 [0,1] 这两棵树。1
2
3
4
2
3
4
示例 3:
txt
输入:fruits = [1,2,3,2,2]
输出:4
解释:可以采摘 [2,3,2,2] 这四棵树。
如果从第一棵树开始采摘,则只能采摘 [1,2] 这两棵树。1
2
3
4
2
3
4
示例 4:
txt
输入:fruits = [3,3,3,1,2,1,1,2,3,3,4]
输出:5
解释:可以采摘 [1,2,1,1,2] 这五棵树。1
2
3
2
3
提示:
1 <= fruits.length <= 10^50 <= fruits[i] < fruits.length
2. 🎯 s.1 - 滑动窗口
c
int totalFruit(int* fruits, int fruitsSize) {
int count[100001];
memset(count, 0, sizeof(count));
int res = 0, left = 0, types = 0;
for (int right = 0; right < fruitsSize; right++) {
if (count[fruits[right]]++ == 0) types++;
while (types > 2) {
if (--count[fruits[left]] == 0) types--;
left++;
}
int len = right - left + 1;
if (len > res) res = len;
}
return res;
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15
js
/**
* @param {number[]} fruits
* @return {number}
*/
var totalFruit = function (fruits) {
const map = new Map()
let res = 0,
left = 0
for (let right = 0; right < fruits.length; right++) {
map.set(fruits[right], (map.get(fruits[right]) || 0) + 1)
while (map.size > 2) {
const cnt = map.get(fruits[left]) - 1
if (cnt === 0) map.delete(fruits[left])
else map.set(fruits[left], cnt)
left++
}
res = Math.max(res, right - left + 1)
}
return res
}1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
py
class Solution:
def totalFruit(self, fruits: List[int]) -> int:
from collections import defaultdict
count = defaultdict(int)
res = left = 0
for right, f in enumerate(fruits):
count[f] += 1
while len(count) > 2:
count[fruits[left]] -= 1
if count[fruits[left]] == 0:
del count[fruits[left]]
left += 1
res = max(res, right - left + 1)
return res1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
- 时间复杂度:
,其中 n 是数组长度 - 空间复杂度:
,窗口内最多 3 种水果
算法思路:
- 滑动窗口维护最多包含 2 种水果的子数组
- 右指针扩展,左指针收缩直到种类 ≤ 2,更新最大长度