Write the state and transition for a line of choices: decode ways, a circle of houses, deleting to earn, travel passes and the number of increasing runs.
You work on a fitness app that plans training days. Each day is a rest, an easy workout or a hard workout. A rest earns 0 points, and each workout earns points that differ from day to day.
Your team lead says: "A hard workout needs a rest day directly before it, so it cannot follow any workout. Which plan earns the most points?"
Start with two days, so you can list every plan. Day 0 earns 3 points for an easy workout and 7 for a hard one. Day 1 earns 4 and 9.
| Plan | Allowed | Points |
|---|---|---|
| rest then rest | yes | 0 |
| rest then easy | yes | 4 |
| rest then hard | yes | 9 |
| easy then rest | yes | 3 |
| easy then easy | yes | 7 |
| easy then hard | no: hard after a workout | - |
| hard then rest | yes | 7 |
| hard then easy | yes | 11 |
| hard then hard | no: hard after a workout | - |
Nine plans, and 7 of them are allowed. The best earns 11 points.
A hard workout on day 1 is allowed only after a rest on day 0. A hard workout on day 0 is always allowed, because no day comes before it.
The first attempt is correct. Try every plan, throw away the ones that break the rule, and keep the largest total. Use itertools.product to make the plans.
from itertools import product
def best_plan(easy, hard):
best = 0
for plan in product("RWH", repeat=len(easy)):
total = 0
valid = True
for i, kind in enumerate(plan):
if kind == "H":
if i > 0 and plan[i - 1] != "R":
valid = False
break
total += hard[i]
elif kind == "W":
total += easy[i]
if valid and total > best:
best = total
return bestNow check the real size. Each day has 3 choices, so n days have 3 to the power n plans. The rule removes some, but not many.
| Days | All plans | Plans that obey the rule |
|---|---|---|
| 5 | 243 | 99 |
| 10 | 59,049 | 8,119 |
| 20 | 3,486,784,401 | 54,608,393 |
| 30 | 205,891,132,094,649 | 367,296,043,199 |
For 30 days there are 367,296,043,199 valid plans. At ten million plans a second that is more than 10 hours for one answer, and a training year has 365 days.
Look at what the first attempt throws away. After you decide the first 20 days, the exact plan for them does not matter to day 21. Two facts matter: the best total so far, and whether day 20 was a rest.
A hiker writes two lines in a notebook each evening. The next day needs those two lines, not the whole route: that is the state.
A hiker plans a long trail with camps. Each evening she writes two lines in a notebook: how many kilometres she has walked in total, and whether she rested last night. The next morning's plan needs those two lines and nothing else.
She does not need the whole route. The camps she slept at in week one, and the paths she took, change nothing about what she may do tomorrow.
This is the idea behind the state of a dynamic programming table: the few numbers the future needs from the past. When the rule only needs the best total, one number is enough. When a rule looks at yesterday's choice, the notebook needs a second line.
Predict what happens
Q A plan for the first 20 days earns 80 points and ends with a hard workout. Which fact about it does day 21 need to know, besides the 80?
Answer: B
A hard workout needs a rest directly before it. So day 21 needs to know whether day 20 was a rest, and nothing about the earlier days. The total alone is not enough, and the rest of the plan is not needed.
The table for a line has one cell, or one small group of cells, for each position. What changes from problem to problem is how a cell is worked out. Four shapes cover most problems that set choices along a line.
| Shape | The question | What a cell holds | How a cell is worked out |
|---|---|---|---|
| Take or skip | The largest total, with no two neighbours | The best total for the first i items |
The larger of best[i - 1] and best[i - 2] plus this item |
| Counting | How many ways | The number of ways for the first i units |
The sum of the cells a last piece can leave |
| The cheapest of several | The least cost | The least cost for the first i units |
The smallest of one cell for each choice, plus its price |
| A pair of numbers | A rule about the last choice | Two numbers, one for each kind of last choice | Each number from the old pair, together |
You met the first shape in the last lesson. The sections below show counting and the cheapest of several, and the next beat shows the pair. Start with counting.
A strip of n units is covered with pieces of given lengths, and the order of the pieces matters. How many ways are there? Take pieces of length 1, 3 and 4 and a strip of 6.
Let ways[i] be the number of ordered ways to cover i units. The last piece has length 1, 3 or 4, and the units before it were covered in some way. So ways[i] = ways[i - 1] + ways[i - 3] + ways[i - 4], using only the cells that exist. Covering no units has one way: place no piece.
| Units | Last piece 1 | Last piece 3 | Last piece 4 | ways[i] |
|---|---|---|---|---|
| 0 | 1 | |||
| 1 | ways[0] = 1 | 1 | ||
| 2 | ways[1] = 1 | 1 | ||
| 3 | ways[2] = 1 | ways[0] = 1 | 2 | |
| 4 | ways[3] = 2 | ways[1] = 1 | ways[0] = 1 | 4 |
| 5 | ways[4] = 4 | ways[2] = 1 | ways[1] = 1 | 6 |
| 6 | ways[5] = 6 | ways[3] = 2 | ways[2] = 1 | 9 |
Six units can be covered in 9 ways. Each cell adds the cells a last piece leaves behind, so the table counts every order once.
Ordered covers with pieces of length one, three and four: each cell adds the cells a last piece leaves behind.
def count_covers(n, lengths):
# [1] ways[i] is the number of ordered ways to cover i units. Covering no units has one way: place no piece.
ways = [0] * (n + 1)
ways[0] = 1
for i in range(1, n + 1):
for length in lengths:
# [2] If the last piece has this length, the first i - length units were covered before it. Add those ways.
if length <= i:
ways[i] += ways[i - length]
# [3] The cell for n is the answer. Every cell it reads is to its left, so the loop has filled it already.
return ways[n]public long countCovers(int n, int[] lengths) {
// [1] ways[i] is the number of ordered ways to cover i units. Covering no units has one way: place no piece.
long[] ways = new long[n + 1];
ways[0] = 1;
for (int i = 1; i <= n; i++) {
for (int length : lengths) {
// [2] If the last piece has this length, the first i - length units were covered before it. Add those ways.
if (length <= i) {
ways[i] += ways[i - length];
}
}
}
// [3] The cell for n is the answer. Every cell it reads is to its left, so the loop has filled it already.
return ways[n];
}long long countCovers(int n, vector<int> lengths) {
// [1] ways[i] is the number of ordered ways to cover i units. Covering no units has one way: place no piece.
vector<long long> ways(n + 1, 0);
ways[0] = 1;
for (int i = 1; i <= n; i++) {
for (int length : lengths) {
// [2] If the last piece has this length, the first i - length units were covered before it. Add those ways.
if (length <= i) {
ways[i] += ways[i - length];
}
}
}
// [3] The cell for n is the answer. Every cell it reads is to its left, so the loop has filled it already.
return ways[n];
}function countCovers(n, lengths) {
// [1] ways[i] is the number of ordered ways to cover i units. Covering no units has one way: place no piece.
const ways = new Array(n + 1).fill(0);
ways[0] = 1;
for (let i = 1; i <= n; i++) {
for (const length of lengths) {
// [2] If the last piece has this length, the first i - length units were covered before it. Add those ways.
if (length <= i) {
ways[i] += ways[i - length];
}
}
}
// [3] The cell for n is the answer. Every cell it reads is to its left, so the loop has filled it already.
return ways[n];
}Exercise · Find the bug: The strip one piece covers. This function counts the ordered ways to cover a strip with pieces of the given lengths. It returns 0 for a strip that one piece covers exactly. Which line is wrong?
def count_covers(n, lengths):
ways = [0] * (n + 1)
ways[0] = 1
for i in range(1, n + 1):
for length in lengths:
if length < i:
ways[i] += ways[i - length]
return ways[n]Step by step: Fewest packs of 1, 4 and 9 for 12 tiles. The animated player loads in your browser.
Replace the sum by the smallest cost, and the same loop finds a cheapest cover. The cell for i units takes the smallest of the cells a last piece can leave, plus the price of that piece.
A shop sells square packs of 1, 4 and 9 tiles. Greedy buys 9, 1, 1 and 1 for 12 tiles, which is four packs. The table finds 4, 4 and 4, which is three packs.
Counting adds, and the cheapest keeps the smallest. The loop, the base case and the order of filling stay the same. Four of the five warm-up problems are one of these two shapes.
Exercise · Predict the output: The cheapest cover of six units. The pieces are 1, 3 and 4 units. The table holds the fewest pieces that cover each length, and 99 stands for "cannot be done yet". What does this print for the lengths 4, 5 and 6?
coins = [1, 3, 4]
target = 6
best = [0] + [99] * target
for s in range(1, target + 1):
for coin in coins:
if coin <= s:
best[s] = min(best[s], best[s - coin] + 1)
print(best[4], best[5], best[6])Pick a problem and step through it forwards and back. The cells a new cell reads from are highlighted and joined to it. The coin problem here stands for any line with several piece sizes: the fewest square packs for a total is the coins 1, 4 and 9.
Try these three, in order:
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
Predict what happens
Q For ordered covers with pieces 1, 3 and 4, the cells ways[3], ways[2] and ways[1] hold 2, 1 and 1. Which cells does ways[4] add?
Answer: B
The last piece has length 1, 3 or 4, so ways[4] adds ways[3], ways[1] and ways[0]. That is 2 + 1 + 1 = 4. Length 2 is not a piece, so ways[2] is not read.
Every line table starts with one question: what does the rest of the line need to know about the part I have already decided? Write the answer as one plain sentence. That sentence is the state.
Go back to the training plan. Today's choices depend on one fact about yesterday: was it a rest? So the state is two numbers for each day.
rested[i] is the best total after i days, when day i - 1 was a rest day.worked[i] is the best total after i days, when day i - 1 was a workout.Both start at 0 before any day, because no day comes before day 0, so any workout is allowed on it. A rest follows any day, so rested[i] takes the larger of the old pair. An easy workout follows any day. A hard workout follows only a rest.
rested[i] = max(rested[i - 1], worked[i - 1])worked[i] = max(max(rested[i - 1], worked[i - 1]) + easy[i - 1], rested[i - 1] + hard[i - 1])Each number holds the best total for plans of its kind. It is built only from numbers for the day before, which are already best.
Why does this give the right answer? A plan for i days is a plan for i - 1 days plus today's choice.
Take the best plan that ends in a rest. Swap its earlier days for the best earlier plan, and the rule still holds. The total cannot go down, and the same argument covers a workout.
Here is the table for five days with these points. Easy: [3, 4, 2, 6, 3]. Hard: [7, 9, 5, 12, 4].
| Day | Easy | Hard | rested | worked |
|---|---|---|---|---|
| 0 | 0 | 0 | ||
| 1 | 3 | 7 | 0 (rest after the larger of 0 and 0) | 7 (easy: 0 + 3 = 3; hard: 0 + 7 = 7) |
| 2 | 4 | 9 | 7 (rest after the larger of 0 and 7) | 11 (easy: 7 + 4 = 11; hard: 0 + 9 = 9) |
| 3 | 2 | 5 | 11 (rest after the larger of 7 and 11) | 13 (easy: 11 + 2 = 13; hard: 7 + 5 = 12) |
| 4 | 6 | 12 | 13 (rest after the larger of 11 and 13) | 23 (easy: 13 + 6 = 19; hard: 11 + 12 = 23) |
| 5 | 3 | 4 | 23 (rest after the larger of 13 and 23) | 26 (easy: 23 + 3 = 26; hard: 13 + 4 = 17) |
The answer is the larger of the two last numbers, 26. The table has two numbers for each day and each is worked out from the old pair, so 5 days take 10 numbers.
Two numbers for each day: the best total ending in a rest, and the best total ending in a workout.
Suppose the state were one number, the best total for the first i days, and each day added the larger of its two workouts. That ignores yesterday.
For easy [1, 1] and hard [5, 5] it adds 10. The best legal plan earns 6: a hard workout on day 0, then an easy one on day 1. The rule needs the second number.
You do not need a table of every day when each day reads only the day before. Two variables are enough. This is the take-or-skip line from the last lesson, written with the pair take and skip.
def best_line(values):
# [1] take is the best total of a plan that takes the item just passed. skip is the best total of a plan that does not. Both start at 0.
take = 0
skip = 0
for value in values:
# [2] Taking this item needs the old skip, because its neighbour is then left out. Skipping keeps the larger old total. Both use the old values.
take, skip = skip + value, max(take, skip)
# [3] The best plan either takes the last item or skips it.
return max(take, skip)public int bestLine(int[] values) {
// [1] take is the best total of a plan that takes the item just passed. skip is the best total of a plan that does not. Both start at 0.
int take = 0;
int skip = 0;
for (int value : values) {
// [2] Taking this item needs the old skip, because its neighbour is then left out. Skipping keeps the larger old total. Both use the old values.
int nextTake = skip + value;
int nextSkip = Math.max(take, skip);
take = nextTake;
skip = nextSkip;
}
// [3] The best plan either takes the last item or skips it.
return Math.max(take, skip);
}int bestLine(vector<int> values) {
// [1] take is the best total of a plan that takes the item just passed. skip is the best total of a plan that does not. Both start at 0.
int take = 0;
int skip = 0;
for (int value : values) {
// [2] Taking this item needs the old skip, because its neighbour is then left out. Skipping keeps the larger old total. Both use the old values.
int nextTake = skip + value;
int nextSkip = max(take, skip);
take = nextTake;
skip = nextSkip;
}
// [3] The best plan either takes the last item or skips it.
return max(take, skip);
}function bestLine(values) {
// [1] take is the best total of a plan that takes the item just passed. skip is the best total of a plan that does not. Both start at 0.
let take = 0;
let skip = 0;
for (const value of values) {
// [2] Taking this item needs the old skip, because its neighbour is then left out. Skipping keeps the larger old total. Both use the old values.
const nextTake = skip + value;
const nextSkip = Math.max(take, skip);
take = nextTake;
skip = nextSkip;
}
// [3] The best plan either takes the last item or skips it.
return Math.max(take, skip);
}Both new numbers use the old values. The next section shows what breaks when they do not.
Exercise · Put it in order: The take-or-skip line. Arrange the lines into a function that returns the largest total of values with no two neighbours taken.
def best_line(values):
take = 0
skip = 0
for value in values:
take, skip = skip + value, max(take, skip)
return max(take, skip)
take, skip = take + value, max(take, skip)Suppose the items stand in a circle, so the last item is a neighbour of the first. A plan cannot use both. So every plan leaves out the first item or the last, and what remains is a line.
Run the line method on the items without the last one, then on the items without the first one, and keep the larger answer. A circle of one item has no neighbour, so it is a special case. The warm-up problem about banners around a square is exactly this.
In a circle the first and last items are neighbours, so solve two lines and keep the larger answer.
Exercise · Break it: Find the input where the circle method fails. This function solves the circle by running the line method twice: without the last item, then without the first. Find an input where it gives the wrong answer.
def best_circle(values):
def best_line(items):
take = skip = 0
for value in items:
take, skip = skip + value, max(take, skip)
return max(take, skip)
return max(best_line(values[:-1]), best_line(values[1:]))Sometimes the choice is not on positions but on values. A queue of tracks carries ratings, and choosing a rating removes every track with that rating and the ratings one above and below.
Count how many tracks have each rating first. Choosing rating v is worth v times its count, and ratings v - 1 and v + 1 are ruled out. The ratings now form a line from 1 up to the largest rating, with take or skip at each value. A rating with no tracks is worth 0 and stays on the line.
Predict what happens
Q Four items stand in a circle with values 5, 1, 1 and 5. Why can a plan not take both 5s?
Answer: B
In a circle the last item is next to the first, so the two 5s are neighbours. Solve the line without the last item and the line without the first item, and keep the larger answer: 6 here.
Predict what happens
Q For easy [3, 4] and hard [7, 9], rested is 0 and worked is 7 after day 1. What is worked after day 2?
Answer: B
A hard workout on day 2 would follow a workout, so it is not allowed. An easy workout adds 4 to the larger old number, 7, which gives 11. Rested after day 2 is 7.
Now write it yourself. The lab has one function, best_training_points(easy, hard). It returns the most points a plan can earn, where every hard workout is on day 0 or follows a rest day.
Here is a small run with easy [3, 4] and hard [7, 9]. Two days, so the answer matches the list of plans in the first beat.
| Day | Easy | Hard | rested | worked |
|---|---|---|---|---|
| 0 | 0 | 0 | ||
| 1 | 3 | 7 | 0 | 7 (hard: 0 + 7) |
| 2 | 4 | 9 | 7 | 11 |
The answer for two days is 11, the larger of the last two numbers.
Three rules keep it correct:
rested, never to the old worked.Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
The cost of a line table is the number of positions times the work for each position.
| Question | Take or skip | Counting, or the cheapest of several |
|---|---|---|
| Time | O(n): two cells read for each position | O(n × k): one cell read for each of k choices |
| Memory | O(1) with two numbers, or O(n) for the table | O(n) for the table, or a window as long as the longest piece |
| Steps for n = 100,000 | About 200,000 | About 300,000 for k = 3 |
| What to keep | The last two cells | The cells the longest piece reaches back to |
A pair of numbers costs the same as one number, times two. For the training plan, 100,000 days take about 300,000 small steps.
Use a line table when the items come in a fixed order and a choice depends on the choices before it. The same prefix question must come back many times. Words such as "no two neighbours", "how many ways to cut", "the cheapest cover" and "needs a rest before" are the hint.
Write the state as one sentence first. If one number is not enough, ask what fact about the last choice the future needs.
Do not use a one-dimensional table when a rule reaches back by an amount that grows with the input. An example is "never repeat an item already used". The state then needs the set of used items, and the table is too big. Use backtracking or a different state.
Do not use it when a greedy rule is provably safe, such as choosing the most talks in one room. Greedy is simpler and faster.
best[i] = best[i - 1] + max(easy[i - 1], hard[i - 1]) ignores yesterday. For easy = [1, 1] and hard = [5, 5] it returns 10, which breaks the rule: two hard workouts in a row. The answer is 6. Add the fact the rule needs to the state.
Updating rested before worked lets the new value leak in, and a hard workout follows a workout.
rested = max(rested, worked) followed by worked = max(rested + easy[i], rested + hard[i]) makes the second line read the new rested. A hard workout then follows a workout. For easy = [1, 1] and hard = [5, 5] it returns 10, and the answer is 6. Work out both new numbers from the old pair, then assign them.
ways[0] = 0 looks harmless, but covering no units has one way: place no piece. Every cell is built from cells to its left, so every cell stays 0. count_covers(5, [1, 2]) returns 0 instead of 8.
Running the line method on values = [5, 1, 1, 5] takes both 5s and returns 10. The first and last items are neighbours in a circle, so the answer is 6. Run the method on the items without the last, then without the first.
ways[i] += ways[i - length] without if length <= i reads ways[-1], which Python takes as the last cell. It adds a cell from the end of the table to a cell at the start. Java throws an index error, and C++ reads outside the array. Test that the piece fits before you read.
Explain the state question in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · The state
Q1/2 A rule says a hard workout needs a rest day directly before it. Which state is enough to plan the best total?
Answer: B
Today's choices depend on one fact about yesterday: was it a rest? So the state needs a number for each answer to that question. One number cannot tell the two cases apart, and the full list is more than the future needs.
Q2/2 Which question picks the state of a line table?
Answer: B
The state is the few numbers the future needs from the past. Ask that question first and write the answer as one plain sentence. The length of the line and the largest item do not say what to remember.
Checkpoint · The pair
Q1/2 For easy = [1, 1] and hard = [5, 5], what is the most points a plan can earn?
Answer: B
A hard workout on day 0 earns 5, and day 1 cannot be hard after a workout. An easy workout on day 1 earns 1, so the total is 6. Two hard workouts in a row would earn 10, which the rule forbids.
Q2/2 In the rested and worked table, which old numbers does a hard workout today add to?
Answer: C
A hard workout needs a rest day before it, so it adds today's hard points to the old rested number. An easy workout may follow any day, so it adds to the larger of the old pair.
Checkpoint · Counting
Q1/2 Ordered covers use pieces of length 1, 3 and 4. The cells ways[0] to ways[3] hold 1, 1, 1 and 2. What does ways[4] hold?
Answer: B
The last piece has length 1, 3 or 4. So ways[4] = ways[3] + ways[1] + ways[0] = 2 + 1 + 1 = 4. A piece of length 2 does not exist, so ways[2] is not read.
Q2/2 Why must ways[0] be 1 and not 0 when counting ordered covers?
Answer: A
Every cell is a sum of cells to its left, and all of them trace back to ways[0]. If ways[0] is 0, every cell stays 0. The one way to cover nothing is the empty cover.
Checkpoint · The cheapest of several
Q1/2 A table counts ways with a sum over the last piece. What changes to find the cheapest cover instead?
Answer: B
The loop, the order of filling and the cells read stay the same. The sum becomes a minimum, and each choice adds its price. The base cell is 0 cost for no units.
Q2/2 Four items stand in a circle with values 5, 1, 1 and 5. What is the largest total with no two neighbours?
Answer: B
The first and last items are neighbours, so a plan takes at most one 5. The line without the last item gives 6, and the line without the first gives 6. The larger is 6. Treating the circle as a line would return 10.
Checkpoint · Values on a line
Q1/2 A queue holds ratings, and choosing rating v removes every track rated v, v - 1 and v + 1. What do you do first?
Answer: B
After counting, the ratings form a line from 1 to the largest rating. Choosing v rules out v - 1 and v + 1, which is take or skip on a line. Highest first is a greedy rule that can fail.
Q2/2 A counting table has n = 100,000 positions and 3 piece lengths. About how many cell reads does it make?
Answer: A
The cost is the number of positions times the cells read for each. Each of the 100,000 positions reads at most 3 cells, so about 300,000 reads.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.