[LeetCode] 904. Fruit Into Baskets_Medium tag: Two pointers
2021-08-04 10:36 Johnson_强生仔仔 阅读(44) 评论(0) 编辑 收藏 举报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.
Example 1:
Input: fruits = [1,2,1]
Output: 3
Explanation: We can pick from all 3 trees.
Example 2:
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:
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].
Example 4:
Input: fruits = [3,3,3,1,2,1,1,2,3,3,4]
Output: 5
Explanation: We can pick from trees [1,2,1,1,2].
Ideas: use set to sore baskets, use d 去存fruit -> index, l, r 为指针,ans 为最后的结果,需要注意的是d的index,并不是first index, 也不是last index,而是最后一个group的fruit的first index,
比如例子[1, 1, 6, 5, 6, 6, 1, 1, 1, 1], 对于6 来说, 在最后5个fruit的时候,d[6] always = 4
Code:
class Solution: def totalFruit(self, fruits: List[int]) -> int: # using two pointers ans, baskets, d, l, r = 0, set(), dict(), 0, 0 while r < len(fruits): if fruits[r] in baskets: if r == 0 or fruits[r] != fruits[r - 1]: d[fruits[r]] = r r += 1 elif len(baskets) < 2: baskets.add(fruits[r]) d[fruits[r]] = r r += 1 elif len(baskets) == 2: baskets = set([fruits[r - 1], fruits[r]]) l = d[fruits[r - 1]] d[fruits[r]] = r ans = max(ans, r - l) return ans