DP solution, from watermelonlh