Fruit Into Baskets
Question
None
Example 1
None
Solution
- ▭
- ▯
all//Fruit Into Baskets.py
# Problem Statement
# You have some fruits, and you want to place them into baskets. You can only place one type of fruit in each basket.
#
# You are given two integer arrays, fruits and baskets, where fruits[i] is the type of fruit that you want to place into the basket baskets[i].
#
# You should return the maximum number of fruits that you can place into the baskets.
#
# Example
# Input: fruits = [1,2,1], baskets = [2,3,2]
# Output: 4
# Explanation: You can place two fruits in basket 0, two fruits in basket 1, and one fruit in basket 2, so the total number of fruits is 4.
#
# Solution
def fruit_into_baskets(fruits, baskets):
# Initialize the variables
max_fruit = 0
start_index = 0
seen_fruits = {}
# Iterate over the baskets
for end_index in range(len(baskets)):
# Record the type of fruit in the current basket
current_fruit = fruits[end_index]
# Add the current fruit to the seen fruits
if current_fruit not in seen_fruits:
seen_fruits[current_fruit] = 0
seen_fruits[current_fruit] += 1
# While there are more than two different types of fruits in the seen fruits
while len(seen_fruits) > 2:
# Remove the fruit from the start index
start_fruit = fruits[start_index]
seen_fruits[start_fruit] -= 1
if seen_fruits[start_fruit] == 0:
del seen_fruits[start_fruit]
# Move the start index
start_index += 1
# Update the maximum number of fruits
max_fruit = max(max_fruit, end_index - start_index + 1)
return max_fruit
all//Fruit Into Baskets.py
# Problem Statement
# You have some fruits, and you want to place them into baskets. You can only place one type of fruit in each basket.
#
# You are given two integer arrays, fruits and baskets, where fruits[i] is the type of fruit that you want to place into the basket baskets[i].
#
# You should return the maximum number of fruits that you can place into the baskets.
#
# Example
# Input: fruits = [1,2,1], baskets = [2,3,2]
# Output: 4
# Explanation: You can place two fruits in basket 0, two fruits in basket 1, and one fruit in basket 2, so the total number of fruits is 4.
#
# Solution
def fruit_into_baskets(fruits, baskets):
# Initialize the variables
max_fruit = 0
start_index = 0
seen_fruits = {}
# Iterate over the baskets
for end_index in range(len(baskets)):
# Record the type of fruit in the current basket
current_fruit = fruits[end_index]
# Add the current fruit to the seen fruits
if current_fruit not in seen_fruits:
seen_fruits[current_fruit] = 0
seen_fruits[current_fruit] += 1
# While there are more than two different types of fruits in the seen fruits
while len(seen_fruits) > 2:
# Remove the fruit from the start index
start_fruit = fruits[start_index]
seen_fruits[start_fruit] -= 1
if seen_fruits[start_fruit] == 0:
del seen_fruits[start_fruit]
# Move the start index
start_index += 1
# Update the maximum number of fruits
max_fruit = max(max_fruit, end_index - start_index + 1)
return max_fruit