You are given an integer array nums and your task is to transform it into a non-decreasing (sorted) array using a special mathematical operation.
The Operation: You can select any element and divide it by its greatest proper divisor. A proper divisor of a number x is any positive divisor that is strictly less than x.
Examples of proper divisors:
- For
12: proper divisors are1, 2, 3, 4, 6(greatest is6) - For
15: proper divisors are1, 3, 5(greatest is5) - For prime numbers like
7: only proper divisor is1
Your goal is to find the minimum number of operations needed to make the array non-decreasing. If it's impossible, return -1.
Key insight: When you divide a number by its greatest proper divisor, you're essentially reducing it to its smallest prime factor!
Input & Output
Visualization
Time & Space Complexity
For each element, we might need to find greatest proper divisor multiple times. Finding GPD takes O(โn) time.
Only using constant extra space for variables
Constraints
- 1 โค nums.length โค 105
- 2 โค nums[i] โค 106
- All elements are at least 2 (no need to handle 1 or negative numbers)