Here's an O(n^2)
-time algorithm, where n
is the length of the array. I retract my comment that there's "probably" a faster one.
There's a simpler O(n^4)
-time algorithm that illustrates the main idea of the dynamic program. We prepare a table of entries T(i, j)
where the i, j
entry contains the maximum number of groups into which the array elements indexed [0, j)
can be grouped suitably in such a way that the last group has indexes [i, j)
.
We have a recurrence
T(0, j) = 1 for all j
T(i, j) = max T(h, i) + 1,
h : S(h, i) ≥ S(i, j)
where S(i, j)
is the sum of array elements indexed [i, j)
, and an empty max is taken to be minus infinity. The answer is
max T(i, n).
i
We get to O(n^4)
because for O(n^2)
table entries, we compute a maximum over O(n)
sums, each of O(n)
items.
We make two optimizations. The first is easy: update the sum S(h, i)
incrementally as we vary h
. This drops the cost to O(n^3)
. We can do the same for S(i, j)
, but to no effect yet assuming that we sensibly hoisted it out of the max loop.
The second depends on nonnegative entries. For particular i, j
, the set of valid h
is an interval like [0, k)
, possibly empty. For i
fixed and j
decreasing, the sum S(i, j)
is nonincreasing, hence the interval does not shrink. This means that we can update the max incrementally as well, yielding an O(n^2)
-time algorithm.