AmazonOA #334
Regulate Temperatures
Estimated HardJudge-ready
Topics (AI-labelled)Prefix & RangesGreedy
Each operation is exactly one of the following: decrease every element of some non-empty prefix by 1; decrease every element of some non-empty suffix by 1; or increase the whole array by 1. Find the minimum number of operations to make all temperatures 0. A single operation cannot decrease by more than one unit, and you cannot decrease an arbitrary interior range by 1.
Input
The first line contains n and the second line contains temperature. On this site 1≤n≤200000, −10^9≤temperature[i]≤10^9. The raw fully restores the ranges of the prefix/suffix operations, which the cleaned-up HTML had swallowed.
Output
Output a single integer, the answer.
Example 1
Input:
3
2 4 4
Output:
4
Example 2
Input:
4
2 -2 -3 1
Output:
12
Example 3
Input:
2
0 0
Output:
0
Example notes
The answers are 4, 12 and 0. Original example 2 is labeled 10, which is wrong: its first step takes the last temperature from 1 to −2, which already violates the single −1 per operation. This site openly corrects it to 12: three whole-array +1 operations give [5,1,0,4], then the prefix ending at 0 is decreased by 1 four times, the prefix ending at 1 once, and the suffix starting at 3 four times, for 12 operations in total. An independent graph over unit operations confirms this optimum.
Editorial
Loading solution…