Dynamic programming solution