Looking at the posting http://thread.gmane.org/gmane.comp.lang.r.general/175564 I thought it should be possible to formulate this as a mathematic programming problem. The quadratic objective would yield an MIQP. An example formulation could be: http://amsterdamoptimization.com/models/blog/reading.gms. This is not really easy to solve. Even a MIP approximation (minimizing sum of absolute deviations) is not easy: http://amsterdamoptimization.com/models/blog/reading2.gms. Looks like we are loosing against dynamic programming here.