Wiggly Hoseok Caterpillar - Efficiency
InterviewTime limit1sMemory limit512 MB
Choose disjoint consecutive blocks of food, each summing to at least K, to maximize the total sum minus K times the number of blocks.
- Level
Medium6 of 10
- Topics
- Dynamic programming, Prefix sum, Binary search, Greedy
- Solved
- No attempts yet
Problem
The wiggly Hoseok caterpillar is about to crawl to the right along a twig on which N pieces of food are lined up in a row. At the starting moment the Hoseok caterpillar is at position 0, and the i-th piece of food can be reached after crawling to the right for i seconds. It also always advances 1 to the right every second.
The tastier the i-th piece of food is, the more satisfaction the Hoseok caterpillar gains. It is a greedy glutton that knows nothing of moderation, so once it starts eating it must keep eating consecutively, and it stops eating consecutively when the accumulated satisfaction becomes at least the minimum satisfaction K, or when there is no more food left to eat. If the accumulated satisfaction reaches the minimum satisfaction or more, it stores metamorphosis energy equal to the satisfaction exceeding K. Immediately afterward the Hoseok caterpillar's satisfaction returns to 0 and it can eat food again. Even if it has not finished digesting when it has passed the entire twig, regard the metamorphosis energy as already stored at the moment the minimum satisfaction was exceeded.

For example, if 9 pieces of food exist as above, the Hoseok caterpillar plans for the future and boldly gives up the 1st piece of food. Then it starts eating from the 2nd piece and eats through the 3rd, so its satisfaction becomes 9 and it stores 3 energy. For the same reason it also gives up the 4th piece of food, and starting from the 5th it eats consecutively through the 7th, gaining satisfaction 15. This stores 9 metamorphosis energy. If it eats through the 8th and 9th pieces of food, 2 metamorphosis energy is stored. The total 14 metamorphosis energy obtained this way is the maximum for the example above.
Every second the Hoseok caterpillar moves to the right and can pass by food or start eating it. Once it starts eating, it will keep eating until its satisfaction is filled. Which pieces of food should it eat so that the stored metamorphosis energy is maximized?
Input
The first line gives the number of food pieces N and the minimum satisfaction K, separated by a space.
The second line gives the satisfaction values of the 1st through N-th pieces of food in order.
Output
Find the maximum stored metamorphosis energy. If it cannot metamorphose even once, output 0.
Constraints
- 1 ≤ N ≤ 100,000, N is an integer.
- 1 ≤ K ≤ 10^8, K is an integer.
- 0 ≤ each food's satisfaction ≤ 10^8, all satisfaction values are integers.