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^5
1 <= target[i] <= 10^5
The optimal way would be: every time we reduce all the possible positions by the minimum number, then we have 0
s to split the array. Recursively do so to the non-zero split arrays.
Solved after help…
Consider we need to get nums[0]
, after making nums[0]
to 0
, let’s move to nums[1]
:
If nums[0]
is smaller than nums[1]
, then while making nums[0]
we could as well make nums[1]
, so when we arrive at nums[1]
, only nums[1] - nums[0]
is left.
If nums[1]
is smaller than nums[0]
, then while making nums[0]
we could as well make nums[1]
, so when we arrive at nums[1]
, nothing is left.
Time complexity: o ( n ) o(n) o(n)
Space complexity: o ( 1 ) o(1) o(1)
class Solution:
def minNumberOperations(self, target: List[int]) -> int:
def helper(left: int, right: int) -> int:
while left <= right:
if target[left] == 0:
left += 1
elif target[right] == 0:
right -= 1
else:
break
if left > right:
return 0
if left == right:
return target[left]
min_num = min(target[left: right + 1])
cut_indexes = []
start = left
for i in range(left, right + 1):
target[i] -= min_num
if target[i] == 0:
cut_indexes.append((start, i))
start = i
cut_indexes.append((start, i))
res = min_num
for each_start, each_end in cut_indexes:
res += helper(each_start, each_end)
return res
return helper(0, len(target) - 1)
class Solution:
def minNumberOperations(self, target: List[int]) -> int:
res = 0
for i in range(len(target)):
if i - 1 < 0:
res += target[i]
else:
if target[i] > target[i - 1]:
res += target[i] - target[i - 1]
return res