Skip to content

Commit 2f7a794

Browse files
Merge pull request #311 from komi14/main
Create Minimum_Replacements_to_Sort_Array.java
2 parents a5d9672 + 14a82ef commit 2f7a794

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// 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.
2+
3+
// 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].
4+
// Return the minimum number of operations to make an array that is sorted in non-decreasing order.
5+
6+
7+
8+
// Example 1:
9+
10+
// Input: nums = [3,9,3]
11+
// Output: 2
12+
// Explanation: Here are the steps to sort the array in non-decreasing order:
13+
// - From [3,9,3], replace the 9 with 3 and 6 so the array becomes [3,3,6,3]
14+
// - From [3,3,6,3], replace the 6 with 3 and 3 so the array becomes [3,3,3,3,3]
15+
// There are 2 steps to sort the array in non-decreasing order. Therefore, we return 2.
16+
17+
// Example 2:
18+
19+
// Input: nums = [1,2,3,4,5]
20+
// Output: 0
21+
// Explanation: The array is already in non-decreasing order. Therefore, we return 0.
22+
23+
public class Solution {
24+
public long minimumReplacement(int[] nums) {
25+
long operations = 0;
26+
long prev_bound = nums[nums.length - 1];
27+
28+
for (int i = nums.length - 2; i >= 0; i--) {
29+
long num = nums[i];
30+
long no_of_times = (num + prev_bound - 1) / prev_bound;
31+
operations += no_of_times - 1;
32+
prev_bound = num / no_of_times;
33+
}
34+
35+
return operations;
36+
}
37+
}

0 commit comments

Comments
 (0)