904. Fruit Into Baskets #2010
-
Topics: 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 You want to collect as much fruit as possible. However, the owner has some strict rules that you must follow:
Given the integer array Example 1:
Example 2:
Example 3:
Constraints:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to find the maximum number of fruits we can collect from a row of fruit trees while adhering to specific constraints. The constraints are that we can only collect two types of fruits, and we must pick fruits from every tree starting from a chosen tree moving to the right until we encounter a tree that produces a fruit type not in our baskets. Approach
Let's implement this solution in PHP: 904. Fruit Into Baskets <?php
/**
* @param Integer[] $fruits
* @return Integer
*/
function totalFruit($fruits) {
$n = count($fruits);
$left = 0;
$maxFruits = 0;
$countMap = [];
for ($right = 0; $right < $n; $right++) {
$fruit = $fruits[$right];
if (!isset($countMap[$fruit])) {
$countMap[$fruit] = 0;
}
$countMap[$fruit]++;
while (count($countMap) > 2) {
$leftFruit = $fruits[$left];
$countMap[$leftFruit]--;
if ($countMap[$leftFruit] == 0) {
unset($countMap[$leftFruit]);
}
$left++;
}
$windowSize = $right - $left + 1;
if ($windowSize > $maxFruits) {
$maxFruits = $windowSize;
}
}
return $maxFruits;
}
// Test cases
echo totalFruit([1, 2, 1]) . "\n"; // Output: 3
echo totalFruit([0, 1, 2, 2]) . "\n"; // Output: 3
echo totalFruit([1, 2, 3, 2, 2]) . "\n"; // Output: 4
?> Explanation:
This approach efficiently processes the array in linear time, O(n), where n is the number of trees, by leveraging the sliding window technique and a hash map for constant-time lookups and updates. The space complexity is O(1) since the hash map stores at most three fruit types at any time. |
Beta Was this translation helpful? Give feedback.
We need to find the maximum number of fruits we can collect from a row of fruit trees while adhering to specific constraints. The constraints are that we can only collect two types of fruits, and we must pick fruits from every tree starting from a chosen tree moving to the right until we encounter a tree that produces a fruit type not in our baskets.
Approach
left
andright
, which represent the current range of trees under consideration.