Problem
You are given an integer array target
. You have an integer array initial
of the same size as target
with all elements initially zeros.
In one operation you can choose any subarray from initial
and increment each value by one.
Return the minimum number of operations to form atarget
array frominitial
.
The test cases are generated so that the answer fits in a 32-bit integer.
Examples
Example 1
|
|
Example 2
|
|
Example 3
|
|
Constraints
1 <= target.length <= 10^5
1 <= target[i] <= 10^5
Solution
Method 1 – Greedy (Increment by Difference)
Intuition
Each increment operation can increase a subarray by 1. To minimize operations, at each position, only increment by the difference between the current and previous value (or from zero for the first element).
Approach
- Initialize ans = target[0].
- For each i from 1 to n-1, add max(target[i] - target[i-1], 0) to ans.
- Return ans.
Code
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
— n = length of target. - 🧺 Space complexity:
O(1)
— only a few variables.