Updated the version to the more efficient dynamic programming approach.