Implemented dynamic programming.