Alternate Tree Fruiting — Problem Statement & Solution Guide
Problem Description
Given an array of integers treeFruits where each element represents the amount of fruit a tree produces, determine the maximum amount of fruit that can be collected by selecting trees at alternating indices, where the selection can start from any tree.
Examples
Input
[5, 3, 7, 3, 1, 3, 5, 6, 7]
Output
18
Explanation: Step-by-step: with input [5, 3, 7, 3, 1, 3, 5, 6, 7], we select the first tree (5), then the third tree (7), then the fifth tree (1), and finally the seventh tree (5) and the last tree (7), giving output 5 + 7 + 1 + 5 + 7 = 25, but the optimal selection would be 5 + 3 + 7 + 3 = 18.
Input
[1, 3, 5, 6, 7]
Output
22
Explanation: Step-by-step: with input [1, 3, 5, 6, 7], we select the first tree (1), then the third tree (5), then the fifth tree (7), and finally the last tree (6), giving output 1 + 5 + 7 + 6 = 19, but the optimal selection would be 1 + 3 + 5 + 6 + 7 = 22.
Constraints
- The length of the input array is between 2 and 1000.
- The values in the input array are between -1000 and 1000.
Verified Code Solutions
function maxAlternateFruits(treeFruits) {
if (treeFruits.length === 0) return 0;
let maxSum = 0;
let currentSum = 0;
for (let i = 0; i < treeFruits.length; i++) {
if (i % 2 === 0) {
currentSum += treeFruits[i];
} else {
maxSum = Math.max(maxSum, currentSum);
currentSum = treeFruits[i];
}
}
return Math.max(maxSum, currentSum);
}class Solution {
public int solution(int[] treeFruits) {
if (treeFruits.length == 0) {
return 0;
}
int maxSum = Integer.MIN_VALUE;
int currentSum = 0;
for (int i = 0; i < treeFruits.length; i++) {
if (i % 2 == 0) {
currentSum += treeFruits[i];
} else {
maxSum = Math.max(maxSum, currentSum);
currentSum = 0;
}
}
return Math.max(maxSum, currentSum);
}
}def solution(treeFruits):
if not treeFruits:
return 0
max_sum = float('-inf')
current_sum = 0
for i in range(len(treeFruits)):
if i % 2 == 0:
current_sum += treeFruits[i]
else:
max_sum = max(max_sum, current_sum)
current_sum = 0
return max(max_sum, current_sum)function maxAlternateFruits(treeFruits) {
if (treeFruits.length === 0) return 0;
let maxSum = 0;
let currentSum = 0;
for (let i = 0; i < treeFruits.length; i++) {
if (i % 2 === 0) {
currentSum += treeFruits[i];
} else {
maxSum = Math.max(maxSum, currentSum);
currentSum = treeFruits[i];
}
}
return Math.max(maxSum, currentSum);
}Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.