29/41
Part 6 of 7 · The worked exampleLearn and do

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 - 1 can't run, but every job before that can. So the pay adds to best[i - 1]. Job 0 has nothing before it, so its pay adds to 0.

The larger of the two is best[i + 1]:

iPaySkipTakeBest
040040 + 0 = 4040
1704070 + 0 = 7070
2407040 + 40 = 8080
3308030 + 70 = 100100
45010050 + 80 = 130130

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.