89. No two neighbours
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
Input
fruit = [3, 10, 4, 2, 8]Output
18ExplanationTrees 1 and 4: 10 + 8.
Example 2
Input
fruit = [5, 1, 1, 5]Output
10ExplanationThe two ends, which aren't neighbours.
Example 3
Input
fruit = []Output
0ExplanationNo trees, no fruit.
Constraints
fruithas 0 to 300 whole numbers, each from 0 to 1000.
Submit also runs 9 more tests you can't see.
- Go along the row. For the trees so far, the best total either skips the latest tree (the best up to the tree before it) or picks it (its fruit plus the best up to two trees back).
- So
best(i) = max(best(i - 1), best(i - 2) + fruit[i]): each answer comes from the two before it. - You only ever need the last two answers. Keep them in two variables, both starting at 0, and update them together:
before, best = best, max(best, before + x).
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.