---
# System prepended metadata

title: 2654. Minimum Number of Operations to Make All Array Elements Equal to 1
tags: [Leetcode, Medium, Math]

---

# 2654. Minimum Number of Operations to Make All Array Elements Equal to 1
###### tags: `Leetcode` `Medium` `Math`
Link: https://leetcode.com/problems/minimum-number-of-operations-to-make-all-array-elements-equal-to-1/description/
## 思路 $O(N^2)$
找到最小的gcd为1的subarray
先把这个subarray里变出一个1
接着用这一个1把整个array变成all 1
## Code
```python=
class Solution:
    def minOperations(self, nums: List[int]) -> int:
        ones = nums.count(1)
        if ones: return len(nums)-ones
        minSubarray = math.inf
        for i in range(len(nums)):
            last_gcd = nums[i]
            for j in range(i+1, len(nums)):
                last_gcd = math.gcd(last_gcd, nums[j])
                if last_gcd==1: minSubarray = min(minSubarray, j-i)
        return -1 if minSubarray==math.inf else minSubarray+len(nums)-1

```