713134. Bird and maximum fruit gathering

Easy

Bird and maximum fruit gathering

Summary

In this problem, we are given an array of integers representing the positions of fruits on a tree. The task is to maximize the number of fruits that can be gathered by a bird starting from any node in the tree.

The key concepts involved include arrays and data structures, which is reflected in the tags "Arrays" and "Data Structures".

Detailed Explanation

The problem involves finding the maximum number of fruits that can be gathered by a bird. To solve this, we will use a greedy approach to always choose the fruit that is closest to the current position.

Here's the step-by-step breakdown:

  1. Initialize two variables: max_fruits to keep track of the maximum number of fruits and current_position to keep track of the current position.
  2. Iterate over the array of fruit positions in ascending order.
  3. For each fruit, calculate the distance between the current fruit and the previous one (if it exists). If this distance is greater than 1, update max_fruits to be the maximum of its current value and the number of fruits that can be gathered at this point.
  4. Return max_fruits.

Here's a diagram illustrating the process:

  0  | 2  | 3  | 5  | 6
  ---------
 F1 |    |    | F2 | F3
     |    | F4 |
     | F5 |

The time complexity of this solution is O(n), where n is the number of fruits, since we iterate over the array once. The space complexity is O(1) as we only use a constant amount of space to store our variables.

Optimized Solutions

Java

View on GeeksforGeeks
int maxFruits(int[] positions) {
    int max_fruits = 0;
    int current_position = 0;

    for (int i = 0; i < positions.length; i++) {
        if (positions[i] - current_position > 1) {
            max_fruits = Math.max(max_fruits, i);
        }
        current_position = positions[i];
    }

    return max_fruits;
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.