It's a cool problem. Dynamic programming is used to keep older state memorized.