Refactoring Dynamic Programming impl