1. 解题思路
这一题其实也还蛮简单的,我们只需要考察一下两个数组的差值序列即可。
我们将插值序列分组,使得每一个subarray均为正值或者负值,此时,每一段当中必然要么全部做+1操作,要么全部做-1操作,相互不能交叉利用。
于是,问题就变成了,对于一个同号序列(不妨设均为正值),我们最少需要多少次+1操作才能够构造出来。
这个问题就比较简单了,我们只需要从左往右依次考察每一个元素,如果这个元素 x x x比前方元素 y y y大,那么我们就需要额外进行 x − y x-y x−y次操作才能够得到 x x x,反之,如果 x ≤ y x \leq y x≤y,那么我们就无需进行任何操作,因为在构造前一个元素 y y y的过程中必然经过 x x x,我们可以顺道就把这个元素构造完成。
累加所有所需的构造次数,即可得到我们最终的答案。
2. 代码实现
给出python代码实现如下:
class Solution:
def minimumOperations(self, nums: List[int], target: List[int]) -> int:
diff = [x-y for x, y in zip(nums, target)]
ans = 0
idx, n = 0, len(diff)
while idx < n:
pre = 0
while idx < n and diff[idx] >= 0:
if diff[idx] > pre:
ans += diff[idx] - pre
pre = diff[idx]
idx += 1
pre = 0
while idx < n and diff[idx] < 0:
if diff[idx] < pre:
ans += (pre - diff[idx])
pre = diff[idx]
idx += 1
return ans
提交代码评测得到:耗时771ms,占用内存30.4MB。