A table of best totals: take each job or skip it
Before the real jobs, try the idea on an easy case. Five jobs run back to back: (0, 2), (1, 3), (2, 4), (3, 5) and (4, 6). Each overlaps only the job just before it and the job just after it. They pay 40, 70, 40, 30 and 50.
Let best[i] be the most pay from the first i jobs alone. best[0] is 0: no jobs, no pay. For job i there are two choices:
- Skip it, and the best stays
best[i]. - Take it, and job
i - 1can't run, but every job before that can. So the pay adds tobest[i - 1]. Job 0 has nothing before it, so its pay adds to 0.
The larger of the two is best[i + 1]:
i | Pay | Skip | Take | Best |
|---|---|---|---|---|
| 0 | 40 | 0 | 40 + 0 = 40 | 40 |
| 1 | 70 | 40 | 70 + 0 = 70 | 70 |
| 2 | 40 | 70 | 40 + 40 = 80 | 80 |
| 3 | 30 | 80 | 30 + 70 = 100 | 100 |
| 4 | 50 | 100 | 50 + 80 = 130 | 130 |
The answer is the last entry, 130: jobs 0, 2 and 4. Grabbing the 70 first blocks both its neighbors, and the best you can do around it is 120.
Each entry of best is built from earlier ones. That makes this a dynamic program: a table filled in an order where every entry's inputs are ready.
In the editor, write most_pay_in_a_row(pays). It fills the table for the five jobs.