So the OP's problem in general can be solved by the DP algorithm given in this question. I'll repeat the crux of it here for completeness:
Suppose d[i][j] is solution of the problem when we have items s[1], .., s[i] and j containers. Then:
- d[0][j] = 0 for each j
- d[i][1] = Sum(s[1], ..., s[i]) for each i
- d[i][j] = min(max(d[i-t][j-1], Sum(s[i-t+1], ..., s[i]) over all 1<=t<=i)
However, the naive implementation consumes O(NK) space, which is too much. Fortunately, look at (3): d[_][j]
's value depends only on d[_][j-1]
. This means that once we're done computing all d[_][j]
, we can use the space we were using to store d[_][j-1]
to instead store the values of d[_][j+1]
we're about to compute.
Since the values d[0][j]
are all zero, we don't need to store those either. Hence the only arrays we need to store are the O(N)-sized d[i][1]
, the O(N)-sized array that holds the result from the j-1
th iteration, and the O(N)-sized array that holds the results from the j
th iteration we're currently computing. Total: O(N).
Edit: So first time round, I didn't actually answer the OP's question about how to count the number of containers at max weight. Suppose w[i][j]
holds the max weight of the i,j
th problem, and c[i][j]
is the number of containers which match that max weight. Then:
c[0][j] = j
andw[0][j] = 0
for eachj
c[i][1] = 1
andw[i][1] = Sum(s[1], .., s[i])
for eachi
- Let
u
be equal to thet
chosen in pt (3) above.- If
d[i-u][j-1] > Sum(s[i-u+1], .., s[i])
:- then
c[i][j] = c[i-u][j-1]
andw[i][j] = w[i-u][j-1]
- because the
j
th container with weightSum(s[i-u+1], .., s[i]
is lighter than the heaviest container out of containers1, .., j-1
, which has weightd[i-u][j-1]
.
- then
- If
d[i-u][j-1] < Sum(s[i-u+1], .., s[i])
:- then
c[i][j] = 1
andw[i][j] = Sum(s[i-u+1], .., s[i])
- because the
j
th container with itemss[i-u+1], .., s[i]
is the new heaviest container.
- then
- If If
d[i-u][j-1] == Sum(s[i-u+1], .., s[i])
:- then
c[i][j] = c[i-u][j-1]+1
andw[i][j] = d[i-u][j-1]
- because the
j
th container is the same weight as the previous heaviest container.
- then
- If
Again, we only need to use a constant number of O(N)
sized arrays, for O(N)
time overall.