dynamic programming version of sum cost function back on stream