implemented dynamic programming for piecewise constant