First of all I must mention I've seen some solutions on this site that doesn't work after I checked them or do not match my question since I want to do it in a dynamic programming way.
I've tried all things but I'm really lost, I need to partition the given sequence of integers into M continous sub sequences so that the maximal sum of some partition is maximal.
For example: {4,8,7,10,40,15,30,2,1,20} and M = 4 The algorithm should generate {4,8,7,10}{40}{15,30}{2,1,20} because now the maximum sum is 15 + 30 = 45. Again, I mention that I've seen a post on this site which didn't work. Thank you for all the help!
A straight forward dynamic programming solutions:
The state is (i, j)
, where i
is the last element of the current partition and j
is the number of parts there're in partition.
The value of the state is the maximum sum so far.
The transitions are max(f(i, j), sum(i + 1, k)) -> f(k, j + 1)
(it means that we take the [i + 1, k]
part).
The answer is f(N, M)
(it means that we took N
elements and created exactly M
groups).
The maximum sum partition can be found by taking the entire sequence and cutting off M-1
one-element partitions on either side. You should do this in a way such that the sum of cut-off elements is minimal.
This gives you a single integer degree of freedom (the number of elements to cut off from the beginning). So you can just iterate this number from 0
thru M - 1
(the number of elements to cut off from the end is then obviously M - 1 - i
) and take the minimum.
In your example, this would result in:
{4}, {8}, {7}, {10, 40, 15, 30, 2, 1, 20}
The maximum sum of any partition is then 118.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.