Leetcode 904. Fruit Into Baskets
You are visiting a farm that has a single row of fruit trees arranged from left to right. The trees are represented as 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 restriction is that each basket can only hold one type of fruit and you have only two baskets. Therefore, you have to choose two types of fruits and collect as many of these fruits as possible from the array.
You need to write a function that returns the maximum number of fruits you can collect using the two baskets.
Input: fruits = [1,2,1]
Output: 3
Explanation: We can collect [1,2,1].
Input: fruits = [0,1,2,2]
Output: 3
Explanation: We can collect [1,2,2].
If we had started at the first tree, we would only collect [0, 1].
Input: fruits = [1,2,3,2,2]
Output: 4
Explanation: We can collect [2,3,2,2].
If we had started at the first tree, we would only collect [1, 2].
1 <= fruits.length <= 10^5
0 <= fruits[i] < fruits.length
fruits
array positive integers?
0 <= fruits[i] < fruits.length
.fruits
is never empty?
1 <= fruits.length
.To solve this problem, we can use the sliding window approach:
right
) and the other to contract the window (left
).left
pointer to reduce the window size until only two types of fruits remain.#include <unordered_map>
#include <vector>
#include <algorithm>
int totalFruit(std::vector<int>& fruits) {
std::unordered_map<int, int> basket;
int left = 0, right = 0, max_fruit = 0;
while (right < fruits.size()) {
basket[fruits[right]]++;
while (basket.size() > 2) {
basket[fruits[left]]--;
if (basket[fruits[left]] == 0) {
basket.erase(fruits[left]);
}
left++;
}
max_fruit = std::max(max_fruit, right - left + 1);
right++;
}
return max_fruit;
}
The time complexity of this approach is O(N), where N
is the length of the fruits
array. This is because both pointers (left
and right
) only move from the start to the end of the array once.
The space complexity is O(1) as the hashmap will at most contain two keys at any time (representing the two types of fruits).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?