Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3e39836

Browse files
authored
Create 3025. Find the Number of Ways to Place People I 1 1
1 parent 6f2766e commit 3e39836

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed
Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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+
};

0 commit comments

Comments
 (0)