Imagine you're a mathematician tasked with simplifying an array of positive integers until every element becomes 1. You have a powerful tool at your disposal: the ability to replace any element with the greatest common divisor (GCD) of itself and its immediate neighbor.
The Challenge: Given an array nums of positive integers, you can perform the following operation any number of times:
- Select an index
iwhere0 โค i < n-1 - Replace either
nums[i]ornums[i+1]withgcd(nums[i], nums[i+1])
Your goal is to find the minimum number of operations needed to make all array elements equal to 1. If it's impossible to achieve this goal, return -1.
Key Insight: The GCD operation can only make numbers smaller or keep them the same, so we need to strategically choose which elements to replace to propagate 1s throughout the array efficiently.
Input & Output
Constraints
- 1 โค nums.length โค 50
- 1 โค nums[i] โค 106
- Adjacent operations only: You can only perform GCD operations on adjacent elements