LeetCode 2654. Minimum Number of Operations to Make All Array Elements Equal to 1 Solution in Java, C++, Python & More | Explanation + Code

CoderIndeed
0
2654. Minimum Number of Operations to Make All Array Elements Equal to 1

Description

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 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.

 

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 <= 50
  • 1 <= nums[i] <= 106

Solutions

Solution 1: Math

We first count the number of 1s in the array nums as cnt. If cnt \gt 0, then we only need n - cnt operations to turn the entire array into 1s.

Otherwise, we need to first turn one element in the array into 1, and then the minimum number of remaining operations is n - 1.

Consider how to turn one element in the array into 1 while minimizing the number of operations. In fact, we only need to find a minimum contiguous subarray interval nums[i,..j] such that the greatest common divisor of all elements in the subarray is 1, with the subarray length being mi = min(mi, j - i + 1). Finally, our total number of operations is n - 1 + mi - 1.

The time complexity is O(n × (n + log M)) and the space complexity is O(log M), where n and M are the length of the array nums and the maximum value in the array nums, respectively.

PythonJavaC++GoTypeScriptRust
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(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !