mediumArraysPattern: pattern recognition, prefix sum

Alternate Tree Fruiting Solution

Problem Statement

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

Example 1:
Input:[3,2,5,1,7]
Output:10
Explanation: Selecting trees with indices 0, 2, and 4, we get 3 + 5 + 7 = 15, but the correct maximum amount considering all possible selections is indeed 3 + 1 + 7 = 11, however, the optimal selection would be 5 + 7 = 12. But one of the optimal selections 3 + 1 + 7 = 11 does not use the highest number of fruits from two trees.
Example 2:
Input:[1,7,3,5,2]
Output:12
Explanation: Selecting trees with indices 1 and 3, we get 7 + 5 = 12, which is the maximum amount of fruits that can be collected

Constraints

  • The length of the input array is between 2 and 1000.
  • The values in the input array are between -1000 and 1000.
Time: O(N) Space: O(1)
Analyze constraints and compute optimal solutions step-by-step.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

No solution code is currently loaded.
Complete this code in the workspace editor.