Input: nums =[3,9,3]Output: 2Explanation: Here are the steps to sort the array in non-decreasing order:- From [3,9,3], replace the 9with3 and 6 so the array becomes [3,3,6,3]- From [3,3,6,3], replace the 6with3 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 return2.
To make the array non-decreasing, we process from right to left. For each element, if it’s greater than the next, split it into parts so all are ≤ next. The minimum number of splits is ceil(nums[i]/next) - 1.
#include<vector>#include<cmath>classSolution {
public:longlong minimumReplacement(std::vector<int>& nums) {
int n = nums.size();
longlong ops =0;
int next = nums[n-1];
for (int i = n-2; i >=0; --i) {
if (nums[i] <= next) next = nums[i];
else {
int parts = (nums[i]+next-1)/next;
ops += parts-1;
next = nums[i]/parts;
}
}
return ops;
}
};
classSolution {
publiclongminimumReplacement(int[] nums) {
int n = nums.length, next = nums[n-1];
long ops = 0;
for (int i = n-2; i >= 0; i--) {
if (nums[i]<= next) next = nums[i];
else {
int parts = (nums[i]+next-1)/next;
ops += parts-1;
next = nums[i]/parts;
}
}
return ops;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
classSolution {
funminimumReplacement(nums: IntArray): Long {
var next = nums.last(); var ops = 0Lfor (i in nums.size-2 downTo 0) {
if (nums[i] <= next) next = nums[i]
else {
val parts = (nums[i]+next-1)/next
ops += parts-1 next = nums[i]/parts
}
}
return ops
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution:
defminimumReplacement(self, nums: list[int]) -> int:
ops, next =0, nums[-1]
for i in range(len(nums)-2, -1, -1):
if nums[i] <= next:
next = nums[i]
else:
parts = (nums[i]+next-1)//next
ops += parts-1 next = nums[i]//parts
return ops
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
impl Solution {
pubfnminimum_replacement(nums: Vec<i32>) -> i64 {
let n = nums.len();
letmut ops =0i64;
letmut next = nums[n-1];
for i in (0..n-1).rev() {
if nums[i] <= next { next = nums[i]; }
else {
let parts = (nums[i]+next-1)/next;
ops += (parts-1) asi64;
next = nums[i]/parts;
}
}
ops
}
}