Mountain Trek Route
Time limit2sMemory limit64 MB
Add at most k unit blocks onto circular steps to maximize the drop in total up-and-down height around the loop.
- Level
Hard8 of 10
- Topics
- Greedy, Heap, Union-find
- Solved
- No attempts yet
Problem
A circular mountain cycling trek route was built in the countryside near Almaty. It starts and finishes at the same point. The route is modeled as steps of equal width. Step is horizontal and sits at height meters above sea level. Two neighboring steps may have the same height. The difficulty of the route is the total of every climb and every descent along the closed loop.
The route as built is too hard for tourists. To lower the difficulty you can use blocks. A block is as wide as a step and one meter high. You can put a block on a step or on another block, and you do not have to use every block.
Find the largest possible decrease of the difficulty.
Input
The first line contains the number of steps and the number of blocks . (, )
The second line contains the heights . ()
Output
Print the largest possible decrease of the difficulty on one line.
Hint
In the first example the difficulty of the route is 6: three descents of height 1, and one climb of height 3 that leads from the last step back to the first one. Putting one block on the third step and two blocks on the last step lowers the difficulty by 4. Using all five blocks gives the same answer, and no arrangement lowers the difficulty further.