当前位置: 首页> 汽车> 维修 > Leetcode 3229. Minimum Operations to Make Array Equal to Target

Leetcode 3229. Minimum Operations to Make Array Equal to Target

时间:2025/8/2 2:34:21来源:https://blog.csdn.net/codename_cys/article/details/140592810 浏览次数: 0次
  • Leetcode 3229. Minimum Operations to Make Array Equal to Target
    • 1. 解题思路
    • 2. 代码实现
  • 题目链接:3229. Minimum Operations to Make Array Equal to Target

1. 解题思路

这一题其实也还蛮简单的,我们只需要考察一下两个数组的差值序列即可。

我们将插值序列分组,使得每一个subarray均为正值或者负值,此时,每一段当中必然要么全部做+1操作,要么全部做-1操作,相互不能交叉利用。

于是,问题就变成了,对于一个同号序列(不妨设均为正值),我们最少需要多少次+1操作才能够构造出来。

这个问题就比较简单了,我们只需要从左往右依次考察每一个元素,如果这个元素 x x x比前方元素 y y y大,那么我们就需要额外进行 x − y x-y xy次操作才能够得到 x x x,反之,如果 x ≤ y x \leq y xy,那么我们就无需进行任何操作,因为在构造前一个元素 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 = 0idx, n = 0, len(diff)while idx < n:pre = 0while idx < n and diff[idx] >= 0:if diff[idx] > pre:ans += diff[idx] - prepre = diff[idx]idx += 1pre = 0while idx < n and diff[idx] < 0:if diff[idx] < pre:ans += (pre - diff[idx])pre = diff[idx]idx += 1return ans

提交代码评测得到:耗时771ms,占用内存30.4MB。

关键字:Leetcode 3229. Minimum Operations to Make Array Equal to Target

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: