#3326

Minimum Division Operations to Make Array Non Decreasing

Medium
ArrayMathGreedyNumber TheoryGreedyMath
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log m)
Space
O(1)
O(1)
💡

Intuition

Time O(n log m)Space O(1)

The optimal approach involves iterating backward through the array and using the smallest prime divisor to reduce numbers efficiently. This allows us to minimize the number of operations needed to achieve a non-decreasing order.

⚙️

Algorithm

3 steps
  1. 1Step 1: Iterate through the array from the second last element to the first.
  2. 2Step 2: For each element, check if it is greater than the next element.
  3. 3Step 3: If it is, divide it by its smallest prime divisor until it is less than or equal to the next element, counting operations.
solution.py15 lines
1def min_operations(nums):
2    def smallest_prime_divisor(x):
3        for i in range(2, int(x**0.5) + 1):
4            if x % i == 0:
5                return i
6        return x
7
8    operations = 0
9    n = len(nums)
10    for i in range(n - 2, -1, -1):
11        while nums[i] > nums[i + 1]:
12            spd = smallest_prime_divisor(nums[i])
13            nums[i] //= spd
14            operations += 1
15    return operations

Complexity note: The complexity is O(n log m) where n is the number of elements and m is the maximum value in the array. This is due to the prime factorization process for each number.

  • 1Dividing by the greatest proper divisor or smallest prime divisor helps reduce numbers efficiently.
  • 2Iterating backward allows us to ensure that each element is less than or equal to the next.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.