LeetCode每日一题(2366. Minimum Replacements to Sort the Array)

给定一个整数数组,每次操作可以将数组中的一个元素替换为两个和相等的数字。求使数组非递减排序的最小替换次数。文章详细解析了解题思路和算法实现,适合算法爱好者和面试准备。
摘要由CSDN通过智能技术生成

You are given a 0-indexed integer array nums. In one operation you can replace any element of the array with any two elements that sum to it.

For example, consider nums = [5,6,7]. In one operation, we can replace nums[1] with 2 and 4 and convert nums to [5,2,4,7].
Return the minimum number of operations to make an array that is sorted in non-decreasing order.

Example 1:

Input: nums = [3,9,3]
Output: 2

Explanation: Here are the steps to sort the array in non-decreasing order:

  • From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3]
  • From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3]
    There are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.

Example 2:

Input: nums = [1,2,3,4,5]
Output: 0

Explanation: The array is already in non-decreasing order.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值