added dynamic programming approach