1526. Minimum Number of Increments on Subarrays to Form a Target Array
Description
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 <= 1051 <= target[i] <= 105- The input is generated such that the answer fits inside a 32 bit integer.
Solutions
Solution 1: Dynamic Programming
Thinking
Each operation increments a contiguous range; we must turn zeros into \(target\). Both \(n\) and \(target[i]\) can be \(10^5\), so building the array layer by layer is impossible.
An increment covering \([i,j]\) contributes to the prefix \(target[0..i]\) only when \(target[i]\) exceeds its left neighbor. Hence \(f[i]=f[i-1]+\max(0,target[i]-target[i-1])\) with \(f[0]=target[0]\). The recurrence depends on the previous value alone, so a scan of adjacent rises is enough.
We define \(f[i]\) as the minimum number of operations required to obtain \(target[0,..i]\), initially setting \(f[0] = target[0]\).
For \(target[i]\), if \(target[i] \leq target[i-1]\), then \(f[i] = f[i-1]\); otherwise, \(f[i] = f[i-1] + target[i] - target[i-1]\).
The final answer is \(f[n-1]\).
We notice that \(f[i]\) only depends on \(f[i-1]\), so we can maintain the operation count using just one variable.
The time complexity is \(O(n)\), where \(n\) is the length of the array \(target\). The space complexity is \(O(1)\).
Similar problems:
1 2 3 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 11 | |
1 2 3 4 5 6 7 8 9 10 11 | |