book-notes

Chapter 9 - Dynamic programming

The knapsack problem

You have three items that you can put into the knapsack. What items should you steal so that you steal the maximum money’s worth of goods?

Screen Shot 2022-07-14 at 7.46.26 AM.png

The simple solution

Dynamic programming

  1 2 3 4
Guitar (1500, 1 lbs) 1500 1500 1500 1500
Stereo(3000, 4lbs) 1500 1500 1500 3000
Laptop(2000, 3 lbs) 1500 1500 2000 3500

Screen Shot 2022-07-14 at 7.54.59 AM.png

Take aways

Long common substring

Suppose someone missspelled the world on the dictionary.com. You want to be able to guess what word they meant. Type: HISH , you are guessing it’s FISH or VISTA

  1. Making a grid
    1. What’s the value of the cells?
    2. How to divide the problem?
    3. What are the aexes of the gird?
    4. You are trying to find the longes substring that 2 words have in common

The cell: the length of the longest substring that 2 strings have in common

  H I S H
F 0 0 0 0
I 0 1 0 0
S 0 0 2 0
H 0 0 0 3
if word_a[i] == word_b[j]: // The letters match.
 cell[i][j] = cell[i-1][j-1] + 1
else:   // The letters dont match.
 cell[i][j] = 0
  V I S T A
F 0 0 0 0 0
I 0 1 0 0 0
S 0 0 2 0 0
H 0 0 0 0 0

Longest commom subsequence

Missspelled FOSH guess for FISH or FORT

  F O S H
F 1 1 1 1
I 1 1 1 1
S 1 1 2 2
H 1 1 2 3

Screen Shot 2022-07-17 at 9.05.08 PM.png

if word_a[i] == word_b[j]: // The letters match.
 cell[i][j] = cell[i-1][j-1] + 1
else: // The letters dont match.
 cell[i][j] = max(cell[i-1][j], cell[i][j-1])

Recap