aka segmentation dp
this is prefix dp as opposed to internal dp because we operate on prefixes ( rather than intervals — any arbitary split that is not a prefix )
a ggeneral sementation dp is optimising something over segments
is the general idea of a segmentation dp is the cost of adding a new sement from to , and we then optimise over any count of segments in the prefix.
problems
max sum of k disjoin segments
problem: https://atcoder.jp/contests/abc466/tasks/abc466_e
the original problem was about flipping and maximising sum there, which can be modeled as where aka the gain on flip. Obvious to see that optimal solution will have disjoin ranges ( or can be represented using disjoin ranges ).
recurrence
Define as the maximum sum using exactly disjoint segments, where the last segment ends at , so is taken.
There are two choices in the prefix
- If the previous segment also ends at , extend it:
- If the previous segment ends at any earlier position , start a new segment at :
Therefore,
For one segment,
impl notes
- instead of going from to , you can go from 0, it’s just that only would be valid since you can’t build segments without that many elements, but that can be cleanly skipped via a defaul value of and skipping states that read from such transition.
- the max over prefix you can compte as a prefix max at each step.
- if you needed exacly segments, you would use the max over the . If you need atleast, you need to variate that k as well.