Skip to content

3326. Minimum Division Operations to Make Array Non Decreasing 👍

  • Time: $O(n \cdot \sqrt{(\max(\texttt{nums}))})$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
 public:
  int minOperations(vector<int>& nums) {
    int ans = 0;

    for (int i = nums.size() - 2; i >= 0; --i)
      if (nums[i] > nums[i + 1]) {
        const int minDivisor = getMinDivisor(nums[i]);
        if (minDivisor > nums[i + 1])
          return -1;
        nums[i] = minDivisor;
        ++ans;
      }

    return ans;
  }

 private:
  int getMinDivisor(int num) {
    for (int divisor = 2; divisor <= sqrt(num); ++divisor)
      if (num % divisor == 0)
        return divisor;
    return num;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution {
  public int minOperations(int[] nums) {
    int ans = 0;

    for (int i = nums.length - 2; i >= 0; --i)
      if (nums[i] > nums[i + 1]) {
        final int minDivisor = getMinDivisor(nums[i]);
        if (minDivisor > nums[i + 1])
          return -1;
        nums[i] = minDivisor;
        ++ans;
      }

    return ans;
  }

  private int getMinDivisor(int num) {
    for (int divisor = 2; divisor <= Math.sqrt(num); ++divisor)
      if (num % divisor == 0)
        return divisor;
    return num;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution:
  def minOperations(self, nums: list[int]) -> int:
    ans = 0

    for i in range(len(nums) - 2, -1, -1):
      if nums[i] > nums[i + 1]:
        minDivisor = self._getMinDivisor(nums[i])
        if minDivisor > nums[i + 1]:
          return -1
        nums[i] = minDivisor
        ans += 1

    return ans

  def _getMinDivisor(self, num: int) -> int:
    for divisor in range(2, math.isqrt(num) + 1):
      if num % divisor == 0:
        return divisor
    return num