Just a simple bit of dynamic programming