BackmediumArrays Zomato

Optimal Harvest Solution

Problem Statement

In a farm with a series of trees planted in a straight line, each tree produces a different amount of fruits. Find the maximum amount of fruits that can be collected by selecting alternate trees from the farm, where the selection can start from any tree.

Example 1
Input
[3, 7, 2, 1]
Output
8

Explanation: Step-by-step: with input [3, 7, 2, 1], we start from the first tree with 3 fruits. Then we select the third tree with 2 fruits. The total amount of fruits collected is 3 + 2 = 5. However, we can also start from the second tree with 7 fruits. Then we select the fourth tree with 1 fruit. The total amount of fruits collected is 7 + 1 = 8. Therefore, the maximum amount of fruits collected is 8.

Example 2
Input
[10, 8, 6, 3]
Output
19

Explanation: Step-by-step: with input [10, 8, 6, 3], we start from the first tree with 10 fruits. Then we select the third tree with 6 fruits. The total amount of fruits collected is 10 + 6 = 16. However, we can also start from the second tree with 8 fruits. Then we select the fourth tree with 3 fruits. The total amount of fruits collected is 8 + 3 = 11. We can also start from the third tree with 6 fruits. Then we select the fourth tree with 3 fruits. The total amount of fruits collected is 6 + 3 = 9. The maximum amount of fruits collected is 16.

Constraints

  • The length of the input array is between 2 and 1000.
  • The values in the input array are between -1000 and 1000.
Live Compiler
Loading...
Test Cases & Output
🔒 Sign up to run your code

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free