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 long ans = 0;

    int max = nums.back();
    for (int i = nums.size() - 2; i >= 0; --i) {
      const int ops = (nums[i] - 1) / max;
      ans += ops;
      max = 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 max = nums[nums.length - 1];
    for (int i = nums.length - 2; i >= 0; --i) {
      final int ops = (nums[i] - 1) / max;
      ans += ops;
      max = 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

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

    return ans