Problem · Array
Minimum Halvings for Alternating Parity
Learn this problemProblem statement
You are given an array nums of positive integers. In one operation, choose one index and replace its value with floor(nums[i] / 2). You may operate on the same index more than once.
Make the final array alternate in parity. Either odd indices may hold even values and even indices odd values, or the opposite pattern may be used.
Return the minimum total number of operations.
Function
minHalvingsForAlternatingParity(nums: int[]) → intExamples
Example 1
nums = [6,12,5,10]return = 1Use the pattern odd, even, odd, even. Halve 6 once to obtain 3; the other three values already match the pattern.
Example 2
nums = [3,12,5,10]return = 0The array already follows the pattern odd, even, odd, even.
Example 3
nums = [8,7,4,3]return = 0The array already follows the pattern even, odd, even, odd.
Constraints
1 <= nums.length < 10^51 <= nums[i] <= 10^9