def _dynamic_wrap(items, limit):
    scores, trace = [0], []
    for j in range(len(items)):
        best, psum, index = 0, limit, -1
        for i in reversed(range(j + 1)):
            psum -= items[i]
            score = scores[i] + psum ** 2
            if i == j or score < best and psum >= 0:
                best = score
                index = i

        scores.append(best)
        trace.append(index)

    return _build_indices(trace)


def _build_indices(trace):
    indices, index = [], len(trace) - 1
    while index >= 0:
        indices.append((trace[index], index + 1))
        index = trace[index] - 1

    return indices[::-1]

@@ -114,17 +114,28 @@
 index = 
-0
+float('inf')
 , limit,
@@ -269,18 +269,8 @@
  if 
-i == j or 
 scor
@@ -282,16 +282,17 @@
 est and 
+(
 psum %3E= 
@@ -288,24 +288,35 @@
 d (psum %3E= 0
+ or i == j)
 :%0A          

Make it clearer that exactly one item allows psum < 0