Corrected dynamic programming algorithm