Dynamic programming

idea borrowed from Simon.