Minimum Division Operations to Make Array Non Decreasing Problem
Description
LeetCode Problem 3326.
You are given an integer array nums.
Any positive divisor of a natural number x that is strictly less than x is called a proper divisor of x. For example, 2 is a proper divisor of 4, while 6 is not a proper divisor of 6.
You are allowed to perform an operation any number of times on nums, where in each operation you select any one element from nums and divide it by its greatest proper divisor.
Return the minimum number of operations required to make the array non-decreasing.
If it is not possible to make the array non-decreasing using any number of operations, return -1.
Example 1:
Input: nums = [25,7]
Output: 1
Explanation:
Using a single operation, 25 gets divided by 5 and nums becomes [5, 7].
Example 2:
Input: nums = [7,7,6]
Output: -1
Example 3:
Input: nums = [1,1,1,1]
Output: 0
Constraints:
1 <= nums.length <= 10^51 <= nums[i] <= 10^6
Solution
Approach: Preprocessing + Greedy
One operation replaces x by x / d where d is the greatest proper divisor of x. If x is prime, d = 1 and nothing changes. Otherwise x / d is the smallest prime factor of x, call it lpf[x], which is prime and cannot be reduced further. So every number has just two possible values: itself, or lpf[x] after one operation.
Precompute lpf for every number up to 10^6 with a sieve. Then scan the array from right to left. If nums[i] > nums[i + 1], replace nums[i] by lpf[nums[i]] and count one operation; if it is still greater than nums[i + 1], the task is impossible and the answer is -1. Making each element as large as it can stay is optimal, because it leaves the most room for the elements to its left.
Complexity: O(M log log M) for the sieve, where M = 10^6, plus O(n) for the scan; O(M) space.
mx = 10**6 + 1
lpf = [0] * (mx + 1)
for i in range(2, mx + 1):
if lpf[i] == 0:
for j in range(i, mx + 1, i):
if lpf[j] == 0:
lpf[j] = i
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]:
nums[i] = lpf[nums[i]]
if nums[i] > nums[i + 1]:
return -1
ans += 1
return ans