1011. Layered Increments
A sign painter stacks coloured sheets on a long rail. The rail has n slots, all starting with zero sheets, and target[i] is how many sheets slot i must end up holding.
In one move the painter picks any contiguous stretch of slots and places exactly one extra sheet on every slot in that stretch. Return the smallest number of moves that turns the all-zero rail into target.
Slots with a target of zero must never receive a sheet. Your solution should run in O(n) time with O(1) extra space.
Example 1
- Input:
- target = [2,7,7,3,8,1]
- Output:
- 12
- Explanation:
One pass lifts everything to 2, five more passes cover positions 1 to 2 and then 4 to 4, and the jump 3 to 8 needs five fresh passes: 2 + 5 + 5 = 12.
Example 2
- Input:
- target = [5,0,5,0,5]
- Output:
- 15
- Explanation:
The three tall columns are separated by zeros, so each needs its own five passes: 15 in total.
Constraints
1 ≤ n ≤ 105
0 ≤ target[i] ≤ 5000
The answer fits in a 32-bit signed integer.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(1)