Sunny Orchard Row

Easydynamic programmingAlso known as House Robber

A community garden has one long row of plots for fruit trees. From soil tests and sunlight, the gardeners know how many kilograms of fruit a tree would give in each plot. The catch: a tree crowds the roots of its neighbours, so two trees in plots right next to each other both do badly. So the gardeners never plant in two neighbouring plots.

If they choose the plots well, how much fruit can the row give?

Your task

Write maxHarvest(yields). yields[i] is the harvest in kilograms if plot i gets a tree. Choose any set of plots with no two neighbours (plots i and i + 1) both chosen, and return the largest possible total harvest.

You may leave plots empty. An empty row gives 0.

maxHarvest(yields: int[]) → int

Examples

Example 1
Input
yields = [6, 2, 3, 9, 1]
Output
15
Why

Plant in plots 0 and 3: 6 + 9 = 15. Planting every other plot gives 6 + 3 + 1 = 10 or 2 + 9 = 11. The best choice leaves two plots in a row empty (plots 1 and 2), which the every-other pattern never does.

Example 2
Input
yields = [4, 7, 4]
Output
8
Why

The best single plot is 7, but taking it blocks both neighbours. Taking the two 4s gives 8, which is more.

Constraints

  • 0 ≤ yields.length ≤ 1,000
  • 0 ≤ yields[i] ≤ 10,000
Start with brute force

Try every subset of plots, skip the ones with two neighbours, and keep the best total. With 1,000 plots there are 2¹⁰⁰⁰ subsets, far too many. Even the valid ones grow exponentially.

Two shortcuts look tempting and are wrong. Taking every other plot fails on [6, 2, 3, 9, 1]. Grabbing the biggest yield first fails on [4, 7, 4].

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code