Minimum Number of Operations to Make All Array Elements Equal to 1 Problem
Description
LeetCode Problem 2654.
You are given a 0-indexed array nums consisting of positive integers. You can do the following operation on the array any number of times:
- Select an index
isuch that0 <= i < n - 1and replace either ofnums[i]ornums[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.
Example 1:
Input: nums = [2,6,3,4]
Output: 4
Explanation: We can do the following operations:
- Choose index i = 2 and replace nums[2] with gcd(3,4) = 1. Now we have nums = [2,6,1,4].
- Choose index i = 1 and replace nums[1] with gcd(6,1) = 1. Now we have nums = [2,1,1,4].
- Choose index i = 0 and replace nums[0] with gcd(2,1) = 1. Now we have nums = [1,1,1,4].
- Choose index i = 2 and replace nums[3] with gcd(1,4) = 1. Now we have nums = [1,1,1,1].
Example 2:
Input: nums = [2,10,6,14]
Output: -1
Explanation: It can be shown that it is impossible to make all the elements equal to 1.
Constraints:
2 <= nums.length <= 501 <= nums[i] <= 10^6
Solution
Approach: Math
If the array already contains cnt ones, each other element can be turned into 1 with one operation next to a 1, so the answer is n - cnt.
Otherwise we first need to create one 1. That takes len - 1 operations on the shortest subarray whose gcd is 1 (found by trying every start i and extending j while keeping the running gcd). If no such subarray exists, return -1. After that the remaining n - 1 elements need one operation each, for a total of n - 1 + len - 1.
Complexity: O(n * (n + log M)) time and O(log M) space, where M is the maximum value.
from math import gcd
class Solution:
def minOperations(self, nums: List[int]) -> int:
n = len(nums)
cnt = nums.count(1)
if cnt:
return n - cnt
mi = n + 1
for i in range(n):
g = 0
for j in range(i, n):
g = gcd(g, nums[j])
if g == 1:
mi = min(mi, j - i + 1)
return -1 if mi > n else n - 1 + mi - 1