You are given an array of integers fruits
where each element represents the type of a fruit. You are also given two integers k
and m
.
Your task is to collect m
fruits using two baskets while respecting the following rules:
m
fruits, you cannot pick any more fruits from the array.Write a function totalFruit(fruits: List[int], m: int, k: int) -> int
to calculate the maximum number of fruits you can collect.
Example
Input: fruits = [1, 2, 3, 4, 5, 6, 3, 4, 5], m = 2, k = 1
Output: 6
Note
In the given example, we can pick fruits 1 to 6, which makes a total of 6 fruits. We start by picking fruit 1
into the first basket and then pick fruits 2, 3, 4, 5, 6
into the second basket. The remaining fruits cannot be picked because we already have m = 2
fruits.
To solve this problem, we can use the sliding window technique. We will iterate through the array and keep track of the types of fruits in the current window using a dictionary. We will also keep track of the maximum number of fruits we can collect.
Here are the step-by-step details of the solution:
max_fruits = 0
, window_start = 0
, and fruit_counts = {}
.window_end
as the end index of the window.window_end
, add it to the fruit_counts
dictionary with its count.fruit_counts
dictionary has more than k
distinct fruits. If it does, we need to shrink the window from the window_start
to exclude the leftmost fruit.
window_start
in the fruit_counts
dictionary.fruit_counts
dictionary.window_start
to move the window rightwards.window_start
from window_end
and add 1
to the count.max_fruits
with the maximum value between max_fruits
and the number of fruits in the current window.max_fruits
) is greater than or equal to m
, stop the iteration as we cannot collect more than m
fruits.max_fruits
as the maximum number of fruits collected.Let's implement this solution in Python: