You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardexpand all lines: solution/2100-2199/2197.Replace Non-Coprime Numbers in Array/README_EN.md
+138
Original file line number
Diff line number
Diff line change
@@ -62,4 +62,142 @@ Note that there are other ways to obtain the same resultant array.
62
62
63
63
## Solutions
64
64
65
+
### Solution 1: Stack
66
+
67
+
If there exist three adjacent numbers $x$, $y$, $z$ that can be merged, then the result of first merging $x$ and $y$, then merging $z$, is the same as the result of first merging $y$ and $z$, then merging $x$. Both results are $\text{LCM}(x, y, z)$.
68
+
69
+
Therefore, we can always prefer to merge the adjacent numbers on the left, and then merge the result with the adjacent number on the right.
70
+
71
+
We use a stack to simulate this process. We traverse the array, and for each number, we push it into the stack. Then we continuously check whether the top two numbers of the stack are coprime. If they are not coprime, we pop these two numbers out of the stack, and then push their least common multiple into the stack, until the top two numbers of the stack are coprime, or there are less than two elements in the stack.
72
+
73
+
The final elements in the stack are the final result.
74
+
75
+
The time complexity is $O(n \times \log M)$, and the space complexity is $O(n)$. Where $M$ is the maximum value in the array.
0 commit comments