100 XP

89. No two neighbours

Advanced dynamic programming

A row of fruit trees stands along a path, and fruit[i] is how much fruit tree i carries. You may pick from any trees you like, but never from two trees that stand side by side: picking a tree leaves both of its neighbours alone.

Write a function best_harvest(fruit) that returns the most fruit you can pick.

  • You may pick from no trees at all, so an empty row gives 0.
  • The best choice isn't always every other tree: in [5, 1, 1, 5] the best is the two ends, 10.
  • Picking the biggest tree first doesn't always work either. Think about each tree in turn: pick it, or skip it?

Example 1

Inputfruit = [3, 10, 4, 2, 8]
Output18
ExplanationTrees 1 and 4: 10 + 8.

Example 2

Inputfruit = [5, 1, 1, 5]
Output10
ExplanationThe two ends, which aren't neighbours.

Example 3

Inputfruit = []
Output0
ExplanationNo trees, no fruit.

Constraints

  • fruit has 0 to 300 whole numbers, each from 0 to 1000.

Submit also runs 9 more tests you can't see.

Code
def best_harvest(fruit):
    """Find the most fruit without two neighbours.

    fruit: list of int, the fruit on each tree in a row
    Returns: int, the largest total from trees of which
        no two stand side by side
    """
    # Write your code here
    pass