Maximum Non-Adjacent Sum
MediumThis is an extra practice problem. It doesn't have walkthrough slides. You can solve it with the pattern template you already know. Open the hints if you get stuck.
Question
A community garden has a single row of plots. Every plot has a yield, a positive number telling you how much you harvest from it this season.
Two plots next to each other share one fence. You can only disturb that fence once a season. So you can never harvest two plots that are next to each other. Any other set of plots is allowed.
Given the yield of every plot in order, return the largest total yield you can harvest this season.
Input: nums = [5, 1, 1, 5]
Output: 10
Harvest plot 0 and plot 3. They don't share a fence. 5 + 5 = 10 beats any other combination.
Input: nums = [4, 1, 1, 4, 2, 1]
Output: 9
Harvest plot 0, plot 3, and plot 5. None of them are neighbors. Their total is 4 + 4 + 1 = 9.
Input: nums = [3, 7]
Output: 7
With only two plots and a shared fence between them, you can only harvest one. Take the bigger yield.
You might also hear this problem called “House Robber.”
Clarify the problem
What are some questions you'd ask an interviewer?
Understand the problem
Remember to understand the problem and plan your approach before you start coding.