AmazonOA #4
Cart Prefix Zero
Estimated MediumJudge-ready
Topics (AI-labelled)GreedyPrefix & Ranges
One operation chooses a non-empty prefix of the array and adds 1 to all of its elements or subtracts 1 from all of them at once. Find the minimum number of operations needed to turn the whole integer array into 0. The array may contain negative numbers.
Input
The first line contains n (1..100000), and the second line contains n integers (−10⁹..10⁹). The answer may exceed the range of a 32-bit signed integer.
Output
Output a single integer, the answer required by the problem.
Example 1
Input:
5
3 2 0 0 -1
Output:
5
Example 2
Input:
1
0
Output:
0
Example 3
Input:
2
-2 2
Output:
6
Example notes
The differences in example 1 are 1, 2, 0, 1, −1, and the sum of their absolute values is 5.
Editorial
Loading solution…