You are given a 0-indexed array nums consisiting of positive integers. You can do the following operation on the array any number of times:
Select an index i such that 0 <= i < n - 1 and replace either of nums[i] or nums[i+1] with their gcd value.
Return the minimum number of operations to make all elements of nums equal to 1. If it is impossible, return -1.
The gcd of two integers is the greatest common divisor of the two integers.
Input: nums = [2,6,3,4]
Output: 4
이 문제의 풀이는 세 가지 경우로 나눌 수 있다.
배열의 길이 - 1의 개수 가 된다.이 경우엔 먼저 1을 만들어야 한다.
가능한 모든 부분 배열에 대해 GCD를 계산하며 1이 되는 최소 길이를 찾는다.
그 길이가 best라면, 전체 연산 횟수는 N + best - 1 이 된다.
best는 1을 만들기 위한 추가 연산 수이고,N은 이후 남은 수를 모두 1로 만드는 데 필요한 연산 수이다.class Solution:
def minOperations(self, nums: List[int]) -> int:
N = len(nums)
# 전체 배열의 GCD 계산
acc = nums[0]
for i in range(1, N):
acc = gcd(acc, nums[i])
# 모든 수의 GCD가 1이 아니라면 불가능
if acc != 1:
return -1
# 이미 1이 존재하는 경우
one_count = nums.count(1)
if one_count > 0:
return N - one_count
# 1을 만들기 위한 최소 길이의 부분 배열 탐색
best = float('inf')
for i in range(N - 1):
g = nums[i]
for j in range(i + 1, N):
g = gcd(g, nums[j])
if g == 1:
best = min(best, j - i)
break
return N + best - 1