find best piecewise constant vector more elegantly