Optimized dynamic programming solution