Minimum Operations to Make Every Array Element One
Updated
Problem statement
You are given an array of positive integers, nums. In one operation, you pick two elements that sit next to each other. Then you replace either one of them with their greatest common divisor (gcd). The gcd of two numbers is the largest number that divides both of them.
Return the fewest operations needed to make every element equal to 1. If that is impossible, return -1.
Function
minOperationsToOne(nums: int[]) → intExamples
Example 1
nums = [2,6,3,4]return = 4No element starts as 1. Only the last pair of neighbours, 3 and the element right after it, has gcd 1. So one operation replaces the last element with that gcd. Now the third element sits next to the new value, and one more operation replaces it with their gcd too. Two more operations do the same for the second and first elements, moving from right to left. So it takes one operation to create a one and three more to spread it. The answer is four.
Example 2
nums = [2,10,6,14]return = -1The gcd of every element is 2, so no operation can create a 1.
Constraints
2 <= nums.length <= 50.1 <= nums[i] <= 10^6.
More Otter.ai interview questions
Similar questions at other companies
- Evenly Schedule Vehicle InspectionsAmazon · PHONE SCREEN
- Minimum Fuel Car AlignmentFivetran · PHONE SCREENFivetran interview questions
- Halve Values Until All Are at Most kAdobe · PHONE SCREENAdobe interview questions
- Minimum Rounds to Complete All TasksInfosys · OAInfosys interview questions
- Minimize Adjacent Squared-Difference Cost with One InsertionMcKinsey & Company · OAMcKinsey & Company interview questions
- Maximize Revenue from Decreasing InventoryChubb · OAChubb interview questions
- Minimum Values with Even Powers of TwoVisa · OAVisa interview questions
- Minimize Adjacent Squared-Difference Cost with One InsertionMicrosoft · OAMicrosoft interview questions
- Minimum Halvings for Alternating ParityIBM · OAIBM interview questions
- Resource AllocationMaven Securities · OAMaven Securities interview questions