Start free

Beyond A level · 10 exercises

Python dynamic programming

Break the problem into smaller ones that repeat, and keep each answer in a table so it is worked out only once.

Decide what one cell of the table means ("the best total using the first i items"), how it follows from earlier cells, and where it starts.

n = 10
ways = [0] * (n + 1)
ways[0] = 1
for i in range(1, n + 1):
    ways[i] = ways[i - 1] + (ways[i - 2] if i >= 2 else 0)
print(ways[n])  # climbing 10 stairs, 1 or 2 at a time

Watch for: Fill the table in an order where every cell it needs is already filled.

Exercises

  1. Longest increasing subsequenceFind the length of the longest strictly increasing subsequence (numbers in order,Expert
  2. Edit distanceThe edit distance is the smallest number of single-letter insertions, deletions andExpert
  3. KnapsackChoose items to put in a bag without going over its capacity, making the total valueExpert
  4. Fewest coinsPay an amount exactly with the fewest coins; every coin value can be used as oftenExpert
  5. Ways to make changeIn how many ways can an amount be made from the coins (each value used any number ofExpert
  6. Longest common subsequenceFind the length of the longest sequence of characters that appears in both texts inExpert
  7. Best stretchFind the largest sum of a non-empty run of neighbouring numbers (Kadane's algorithmExpert
  8. Longest palindrome insideFind the longest part of a text (consecutive characters) that is a palindrome.Expert
  9. Cheapest path downWalk from the top-left to the bottom-right of a grid of costs, moving only right orExpert
  10. Word breakCan the text be split into words that are all in the dictionary (words may be usedExpert
Start with “Longest increasing subsequence”