Skip to content

Commit 1746311

Browse files
committed
Time: 0 ms (100%), Space: 18 MB (12.94%) - LeetHub
1 parent 09a7e84 commit 1746311

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# time complexity: O(n^2)
2+
# space complexity: O(1)
3+
from math import gcd
4+
from typing import List
5+
6+
7+
class Solution:
8+
def minOperations(self, nums: List[int]) -> int:
9+
n = len(nums)
10+
ones = nums.count(1)
11+
if ones:
12+
return n - ones
13+
result = float('inf')
14+
for left in range(n):
15+
temp = nums[left]
16+
for right in range(left + 1, n):
17+
temp = gcd(temp, nums[right])
18+
if temp == 1:
19+
result = min(result, right - left)
20+
if result == float('inf'):
21+
return -1
22+
return result + n - 1
23+
24+
25+
nums = [2, 6, 3, 4]
26+
print(Solution().minOperations(nums))
27+
nums = [2, 10, 6, 14]
28+
print(Solution().minOperations(nums))

0 commit comments

Comments
 (0)