Problem Statement
We are given:
An array arr[] containing the fruit values of trees.
The trees are arranged in a circle, so the first and last trees are also neighbors.
An integer m, representing the maximum number of trees the bird can visit.
The bird can start at any tree and move to neighboring trees. We need to find the maximum total fruit value the bird can collect by visiting at most m trees.
Example
arr = [2, 1, 3, 5, 0, 1, 4]
m = 3
The best choice is:
1 + 3 + 5 = 9
Therefore:
Answer = 9
Key Observation
Since the trees are arranged in a circle, the bird always visits consecutive trees.
For example:
[2, 1, 3, 5, 0, 1, 4]
If m = 3, possible groups include:
2, 1, 3
1, 3, 5
3, 5, 0
5, 0, 1
0, 1, 4
1, 4, 2 ← circular
4, 2, 1 ← circular
So the problem becomes:
Find the maximum sum of m consecutive elements in a circular array.
Because every fruit value is non-negative, using the maximum allowed number of trees is always optimal. Therefore, we use:
k = Math.min(m, n);
If m > n, the bird cannot visit more than n distinct trees, so we consider the entire array.
Sliding Window Technique
A brute-force solution would calculate the sum of every possible group of m trees.
That could take:
O(n × m)
which is too slow when n and m can be as large as 10^6.
Instead, we use a sliding window.
Suppose:
arr = [2, 1, 3, 5, 0, 1, 4]
m = 3
First calculate:
2 + 1 + 3 = 6
Now move the window one position:
[2, 1, 3] → [1, 3, 5]
Instead of calculating 1 + 3 + 5 from scratch:
old sum = 6
remove 2
add 5
new sum = 6 - 2 + 5
= 9
This takes constant time.
Handling the Circular Array
This is the most important part of the problem.
Consider:
arr = [7, 2, 1, 3, 4]
For m = 2, the normal windows are:
7 + 2
2 + 1
1 + 3
3 + 4
But because the array is circular, we also need:
4 + 7
We can handle this without creating another array.
We use:
i % n
For example, if:
n = 5
then:
0 % 5 = 0
1 % 5 = 1
2 % 5 = 2
3 % 5 = 3
4 % 5 = 4
5 % 5 = 0
6 % 5 = 1
So after reaching the last element, % n automatically takes us back to the beginning.
Complete Java Code
import java.util.*;
class Solution {
public int maxFruits(ArrayList<Integer> arr, int m) {
int n = arr.size();
// We cannot visit more than n trees
int k = Math.min(m, n);
// Calculate the first window
int windowSum = 0;
for (int i = 0; i < k; i++) {
windowSum += arr.get(i);
}
int maxSum = windowSum;
// Slide the window around the circular array
for (int i = k; i < n + k - 1; i++) {
// Remove the element leaving the window
windowSum -= arr.get((i - k) % n);
// Add the new element entering the window
windowSum += arr.get(i % n);
maxSum = Math.max(maxSum, windowSum);
}
return maxSum;
}
}

Join the conversation! Your thoughts help the community grow.