Minimum Number of Operations to Make All Array Elements Equal to 1

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
Inputnums = [2,6,3,4]
Output4
By first creating a 1 from adjacent values 3 and 4, the remaining elements can each be converted to 1 using adjacent gcd operations, for a total of 4 operations.
Example 2
Inputnums = [2,10,6,14]
Output-1
It can be shown that it is impossible to make all the elements equal to 1.

Constraints

  • 2 <= nums.length <= 50
  • 1 <= nums[i] <= 10^6

Asked at 2 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate