Skip to content

Non-Adjacent Harvest

Easy#bottom-up-dp#rolling-variables~20 min

The mission

Problem

A harvesting robot drives along a single row of plots, and each plot holds a known yield. Its arm needs a rest after every pick, so it can never harvest two plots that sit next to each other. Return the largest total yield the robot can collect in one pass. Yields are whole numbers from 0 upward, and the row may be empty.

Examples

Input:  yields = [2, 7, 9, 3, 1]
Output: 12
Why:    harvest plots 0, 2 and 4 for 2 + 9 + 1
Input:  yields = [5, 1, 1, 5]
Output: 10
Why:    the two end plots are not neighbours, so both can be taken
Input:  yields = []
Output: 0
Why:    edge case, an empty row yields nothing

Hints

0 / 3

Target time
O(n)
Target space
O(1)

Constraints

  • yields are integers ≥ 0
  • the row may be empty

Stuck on the idea rather than the code? House Robber covers it.

Python 3Ctrl+Enter runs
Custom test case