[LeetCode] Minimum Division Operations to Make Array Non Decreasing

3326. Minimum Division Operations to Make Array Non Decreasing

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.

Sieve of Eratosthenes

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(vector<int>& nums) {
int ma = *max_element(begin(nums), end(nums));
vector<int> best(ma + 1);
for(int i = 2; i * i <= ma; i++) {
for(int j = i * i; j <= ma; j += i) if(best[j] == 0) best[j] = j / i;
}
int res = 0;
for(int i = 1; i < nums.size(); i++) {
if(nums[i] >= nums[i-1]) continue;
int j = i - 1;
while(j >= 0 and nums[j] > nums[j+1]) {
if(best[nums[j]] == 0) return -1;
res++;
nums[j] /= best[nums[j]];
if(nums[j] > nums[j+1]) return -1;
j--;
}
}
return res;
}
};

Math

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
26
27
28
class Solution {
unordered_map<int,int> cache;
int query(int x) {
if(cache.count(x)) return cache[x];
int sq = sqrt(x);
for(int i = 2; i <= sq; i++) {
if(x % i == 0) return cache[x] = x / i;
}
return cache[x] = 0;
}
public:
int minOperations(vector<int>& nums) {
int res = 0;
for(int i = 1; i < nums.size(); i++) {
if(nums[i] >= nums[i-1]) continue;
int j = i - 1;
while(j >= 0 and nums[j] > nums[j+1]) {
int x = query(nums[j]);
if(x == 0) return -1;
res++;
nums[j] /= x;
if(nums[j] > nums[j+1]) return -1;
j--;
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2024/10/20/PS/LeetCode/minimum-division-operations-to-make-array-non-decreasing/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.