Sunny Orchard Row

Easydynamic programmingAlso known as House Robber

A community garden has one long row of plots for fruit trees, and the gardeners know how many kilograms each plot would yield. A tree crowds its neighbours' roots, so they never plant in two neighbouring plots.

What is the largest total harvest the row can 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.

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 those with two neighbours, and keep the best total. 1,000 plots have 2¹⁰⁰⁰ subsets, and even the valid ones grow exponentially.

Two tempting shortcuts are wrong: taking every other plot fails on [6, 2, 3, 9, 1], and 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