File tree Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Expand file tree Collapse file tree 1 file changed +40
-0
lines changed Original file line number Diff line number Diff line change 1+ #include <bits/stdc++.h>
2+ using namespace std;
3+
4+ class Solution {
5+ public:
6+ vector<int> replaceNonCoprimes(vector<int>& nums) {
7+ vector<int> stack;
8+
9+ for (int num : nums) {
10+ stack.push_back(num);
11+
12+ // Merge while top two are non-coprime
13+ while (stack.size() > 1) {
14+ int a = stack.back(); stack.pop_back();
15+ int b = stack.back(); stack.pop_back();
16+ int g = gcd(a, b);
17+
18+ if (g > 1) {
19+ long long l = (1LL * a / g) * b; // lcm
20+ stack.push_back((int)l);
21+ } else {
22+ stack.push_back(b);
23+ stack.push_back(a);
24+ break;
25+ }
26+ }
27+ }
28+ return stack;
29+ }
30+
31+ private:
32+ int gcd(int a, int b) {
33+ while (b != 0) {
34+ int temp = b;
35+ b = a % b;
36+ a = temp;
37+ }
38+ return a;
39+ }
40+ };
You can’t perform that action at this time.
0 commit comments