#2366
Minimum Replacements to Sort the Array
candidate master · 1340 · lc hard +32 · verified · 53.2% accepted · 2,081 likes · top 44%
Description
Given a 0-indexed integer array nums, you may apply the following operation any number of times: choose one element and split it into two positive integers that sum to the original value.
Return the minimum number of such operations needed to make nums non-decreasing.
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. Therefore, we return 0.
Code
1
2
3