Minimum Division Operations to Make Array Non Decreasing - Problem

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.

Input & Output

Example 1 — Basic Violation
$ Input: nums = [25, 7]
Output: 1
💡 Note: 25 > 7 violates non-decreasing. 25's greatest proper divisor is 5, so 25 ÷ 5 = 5. Now [5, 7] is non-decreasing with 1 operation.
Example 2 — Multiple Operations
$ Input: nums = [7, 21, 3]
Output: -1
💡 Note: 21 > 3 violates constraint. 21 ÷ 7 = 3 (1 op), giving [7, 3, 3]. But 7 > 3 and 7 is prime (GPD = 1), so it cannot be reduced further. Return -1.
Example 3 — Already Non-decreasing
$ Input: nums = [1, 2, 3, 4]
Output: 0
💡 Note: Array is already non-decreasing, no operations needed.

Constraints

  • 1 ≤ nums.length ≤ 105
  • 1 ≤ nums[i] ≤ 106

Visualization

Tap to expand
Minimum Division Operations - Greedy Right-to-Left INPUT Array nums: 25 index 0 7 index 1 25 > 7 (NOT non-decreasing) Greatest Proper Divisors: 25: GPD = 5 (25/5 = 5) 5: GPD = 1 (5/1 = 5) 7 is prime (GPD = 1) Goal: Make array non-decreasing a[i] <= a[i+1] for all i ALGORITHM STEPS 1 Start from right Process i = 0 (last check) 2 Compare nums[0], nums[1] 25 > 7? YES - need fix 3 Divide by GPD 25 / 5 = 5 (ops = 1) 25 --[/5]--> 5 5 <= 7? YES - OK! 4 Check completion Array [5, 7] is sorted Total Operations: 1 Minimum achieved! FINAL RESULT Final Array: 5 7 5 <= 7 [OK] Output: 1 Only 1 operation was needed to make array non-decreasing Before: [25, 7] After: [5, 7] Key Insight: Process right-to-left: For each element, if nums[i] > nums[i+1], repeatedly divide nums[i] by its greatest proper divisor until nums[i] <= nums[i+1]. The GPD of n is n/smallest_prime_factor(n). Primes can only become 1 (GPD=1), so if reduction impossible, return -1. Count total divisions as minimum operations. TutorialsPoint - Minimum Division Operations to Make Array Non Decreasing | Greedy Right-to-Left Approach
Asked in
Google 15 Microsoft 12 Amazon 8
8.5K Views
Medium Frequency
~25 min Avg. Time
234 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen