目标
给你一个数组 nums,你可以执行以下操作任意次数:
- 选择 相邻 元素对中 和最小 的一对。如果存在多个这样的对,选择最左边的一个。
- 用它们的和替换这对元素。
返回将数组变为 非递减 所需的 最小操作次数 。
如果一个数组中每个元素都大于或等于它前一个元素(如果存在的话),则称该数组为非递减。
示例 1:
输入: nums = [5,2,3,1]
输出: 2
解释:
元素对 (3,1) 的和最小,为 4。替换后 nums = [5,2,4]。
元素对 (2,4) 的和为 6。替换后 nums = [5,6]。
数组 nums 在两次操作后变为非递减。
示例 2:
输入: nums = [1,2,2]
输出: 0
解释:
数组 nums 已经是非递减的。
说明:
- 1 <= nums.length <= 10^5
- -10^9 <= nums[i] <= 10^9
提示:
- We can perform the simulation using data structures.
- Maintain an array index and value using a map since we need to find the next and previous ones.
- Maintain the indices to be removed using a hash set.
- Maintain the neighbor sums with the smaller indices (set or priority queue).
- Keep the 3 structures in sync during the removals.
思路
代码