-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path16_Replace_Non_Coprime_Numbers_in_Array.cpp
More file actions
74 lines (60 loc) · 2.67 KB
/
Copy path16_Replace_Non_Coprime_Numbers_in_Array.cpp
File metadata and controls
74 lines (60 loc) · 2.67 KB
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// 2197. Replace Non-Coprime Numbers in Array
// You are given an array of integers nums. Perform the following steps:
// Find any two adjacent numbers in nums that are non-coprime.
// If no such numbers are found, stop the process.
// Otherwise, delete the two numbers and replace them with their LCM (Least Common Multiple).
// Repeat this process as long as you keep finding two adjacent non-coprime numbers.
// Return the final modified array. It can be shown that replacing adjacent non-coprime numbers in any arbitrary order will lead to the same result.
// The test cases are generated such that the values in the final array are less than or equal to 108.
// Two values x and y are non-coprime if GCD(x, y) > 1 where GCD(x, y) is the Greatest Common Divisor of x and y.
// Example 1:
// Input: nums = [6,4,3,2,7,6,2]
// Output: [12,7,6]
// Explanation:
// - (6, 4) are non-coprime with LCM(6, 4) = 12. Now, nums = [12,3,2,7,6,2].
// - (12, 3) are non-coprime with LCM(12, 3) = 12. Now, nums = [12,2,7,6,2].
// - (12, 2) are non-coprime with LCM(12, 2) = 12. Now, nums = [12,7,6,2].
// - (6, 2) are non-coprime with LCM(6, 2) = 6. Now, nums = [12,7,6].
// There are no more adjacent non-coprime numbers in nums.
// Thus, the final modified array is [12,7,6].
// Note that there are other ways to obtain the same resultant array.
// Example 2:
// Input: nums = [2,2,1,1,3,3,3]
// Output: [2,1,1,3]
// Explanation:
// - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3,3].
// - (3, 3) are non-coprime with LCM(3, 3) = 3. Now, nums = [2,2,1,1,3].
// - (2, 2) are non-coprime with LCM(2, 2) = 2. Now, nums = [2,1,1,3].
// There are no more adjacent non-coprime numbers in nums.
// Thus, the final modified array is [2,1,1,3].
// Note that there are other ways to obtain the same resultant array.
// Constraints:
// 1 <= nums.length <= 105
// 1 <= nums[i] <= 105
// The test cases are generated such that the values in the final array are less than or equal to 108.
#include <vector>
#include <numeric>
using namespace std;
class Solution {
public:
vector<int> replaceNonCoprimes(vector<int>& nums) {
vector<int> result;
for (int num : nums) {
result.push_back(num);
while (result.size() > 1) {
int a = result.back();
int b = result[result.size() - 2];
int g = gcd(a, b);
if (g > 1) {
result.pop_back();
result.pop_back();
long long lcm = (long long)a / g * b;
result.push_back((int)lcm);
} else {
break;
}
}
}
return result;
}
};