Skip to content

2366. Minimum Replacements to Sort the Array 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution {
 public:
  long long minimumReplacement(vector<int>& nums) {
    long ans = 0;
    int mx = nums.back();

    for (int i = nums.size() - 2; i >= 0; --i) {
      const int ops = (nums[i] - 1) / mx;
      ans += ops;
      mx = nums[i] / (ops + 1);
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
  public long minimumReplacement(int[] nums) {
    long ans = 0;
    int mx = nums[nums.length - 1];

    for (int i = nums.length - 2; i >= 0; --i) {
      final int ops = (nums[i] - 1) / mx;
      ans += ops;
      mx = nums[i] / (ops + 1);
    }

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def minimumReplacement(self, nums: list[int]) -> int:
    ans = 0
    mx = nums[-1]

    for i in range(len(nums) - 2, -1, -1):
      ops = (nums[i] - 1) // mx
      ans += ops
      mx = nums[i] // (ops + 1)

    return ans