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 i-th tree produces.
You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
Given the integer array fruits, return the maximum number of fruits you can pick.
Example 1:
Input: fruits = [1,2,1]
Output: 3Explanation: We can pick from all trees.
Example 2:
Input: fruits = [0,1,2,2]
Output: 3Explanation: 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: 4Explanation: 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].
Constraints:
1 <= fruits.length <= 100,0000 <= fruits[i] < fruits.lengthclass Solution:
def totalFruit(self, fruits: List[int]) -> int:
n = len(fruits)
res = 0
for i in range(n):
types = set()
j = i
while j < n and (len(types) < 2 or fruits[j] in types):
types.add(fruits[j])
j += 1
res = max(res, j - i)
return resclass Solution:
def totalFruit(self, fruits: List[int]) -> int:
count = defaultdict(int)
l, total, res = 0, 0, 0
for r in range(len(fruits)):
count[fruits[r]] += 1
total += 1
while len(count) > 2:
f = fruits[l]
count[f] -= 1
total -= 1
l += 1
if not count[f]:
count.pop(f)
res = max(res, total)
return resclass Solution:
def totalFruit(self, fruits: List[int]) -> int:
count = defaultdict(int)
l = 0
for r in range(len(fruits)):
count[fruits[r]] += 1
if len(count) > 2:
count[fruits[l]] -= 1
if count[fruits[l]] == 0:
count.pop(fruits[l])
l += 1
return len(fruits) - lclass Solution:
def totalFruit(self, fruits: list[int]) -> int:
l = 0
fruit1_lastIdx = 0
fruit2_lastIdx = -1
fruit1 = fruits[0]
fruit2 = -1
total = res = 1
for r in range(len(fruits)):
f = fruits[r]
if f == fruit1:
total += 1
fruit1_lastIdx = r
elif f == fruit2 or fruit2 == -1:
total += 1
fruit2_lastIdx = r
fruit2 = f
else:
if fruit2_lastIdx == min(fruit1_lastIdx, fruit2_lastIdx):
fruit1_lastIdx, fruit2_lastIdx = fruit2_lastIdx, fruit1_lastIdx
fruit1, fruit2 = fruit2, fruit1
total -= (fruit1_lastIdx - l + 1)
l = fruit1_lastIdx + 1
fruit1 = f
fruit1_lastIdx = r
res = max(res, r - l + 1)
return res