Minimum Number of Increments on Subarrays to Form a Target Array Problem
Description
LeetCode Problem 1526.
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 a target array from initial.
The test cases are generated so that the answer fits in a 32-bit integer.
Example 1:
Input: target = [1,2,3,2,1]
Output: 3
Explanation: We need at least 3 operations to form the target array from the initial array.
[0,0,0,0,0] increment 1 from index 0 to 4 (inclusive).
[1,1,1,1,1] increment 1 from index 1 to 3 (inclusive).
[1,2,2,2,1] increment 1 at index 2.
[1,2,3,2,1] target array is formed.
Example 2:
Input: target = [3,1,1,2]
Output: 4
Explanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2]
Example 3:
Input: target = [3,1,5,4,2]
Output: 7
Explanation: [0,0,0,0,0] -> [1,1,1,1,1] -> [2,1,1,1,1] -> [3,1,1,1,1] -> [3,1,2,2,2] -> [3,1,3,3,2] -> [3,1,4,4,2] -> [3,1,5,4,2].
Constraints:
1 <= target.length <= 10^51 <= target[i] <= 10^5- The input is generated such that the answer fits inside a 32 bit integer.
Solution
Approach: Count the Rises
Think of target as a skyline and each operation as laying one horizontal brick across a run of columns. We need to know how many bricks have to start at each position.
- At position
0, nothing is to the left, sotarget[0]operations must start here. - At position
i, the operations that cover positioni - 1can simply be extended to coverias well.- If
target[i] <= target[i - 1], we can extend onlytarget[i]of them and stop the rest, so no new operation is needed. - If
target[i] > target[i - 1], we can extend all of them, buttarget[i] - target[i - 1]new operations must start here.
- If
So the answer is target[0] plus the sum of max(0, target[i] - target[i - 1]) over all i. This is also a lower bound: every rise of d between neighbors can only be explained by d operations that start exactly there, so we cannot do better.
For example [3,1,5,4,2] gives 3 + 0 + 4 + 0 + 0 = 7.
Complexity: O(n) time and O(1) extra space.
class Solution:
def minNumberOperations(self, target: List[int]) -> int:
ans = target[0]
for i in range(1, len(target)):
# only a rise over the left neighbour needs new operations
ans += max(0, target[i] - target[i - 1])
return ans