702888. Bird and maximum fruit gathering
Bird and maximum fruit gathering
Summary
The problem is to find the maximum number of fruits that can be gathered by a bird from a series of trees, given the positions and types of fruits on each tree. The bird can only gather one type of fruit at a time and must move to an adjacent tree after gathering the current fruit.
Detailed Explanation
To solve this problem, we will use a sliding window approach with two pointers. We will maintain two pointers, left and right, that represent the start and end of our current window. Initially, both pointers are set to 0, indicating the first tree.
We iterate through the trees, moving the right pointer to the next tree when we gather a fruit from the current tree. When we gather a fruit, we check if it is the same type as the previous fruit gathered. If not, we move the left pointer to the current tree and update the count of fruits gathered.
Here's a step-by-step breakdown:
- Initialize
leftandrightpointers to 0. - Iterate through the trees:
- For each tree, check if it has fruits of the same type as the previous tree (if
leftpointer is not at the start). - If yes, move the
rightpointer to the next tree. - If no, move the
leftpointer to the current tree and update the count of fruits gathered.
- For each tree, check if it has fruits of the same type as the previous tree (if
- Repeat step 2 until all trees have been processed.
The time complexity of this approach is O(n), where n is the number of trees, since we only need to iterate through each tree once. The space complexity is O(1) as we are not using any extra space that scales with the input size.
Here's a diagram illustrating the sliding window approach:
+---------------+
| Tree 0 |
+---------------+
^
| (left pointer)
+---------------+
| Tree 1 |
+---------------+
^
| (right pointer)
+---------------+
| Tree 2 |
+---------------+
...
Optimized Solutions
Java
public int birdAndFruit(int[] positions, char[][] types) {
int maxFruits = 0;
int left = 0;
for (int right = 0; right < positions.length; right++) {
if (right > 0 && types[right][0] != types[left][0]) {
left = right;
}
maxFruits = Math.max(maxFruits, right - left + 1);
}
return maxFruits;
}