'Dynamic Programming' attempt at a solution