You are given an array of positive integers nums. In one operation you pick any element and replace it with floor(element / 2). You may apply the operation to any element any number of times, and each replacement counts as one operation.
Return the minimum total number of operations needed so that every pair of adjacent elements has different parity, meaning one of the two is even and the other is odd. If it is impossible, return -1.
Function Signature
def min_operations(nums: list[int]) -> int:
Rules
-
Halving uses floor division, so
7
becomes
3
and
1
becomes
0
.
-
An element may be halved all the way down to
0
, and
0
counts as even.
-
Operations on different elements are independent. The answer is the total count over all elements.
-
An array with one element has no adjacent pairs, so it needs no operations.
Constraints
-
1 <= len(nums) <= 10^5
-
1 <= nums[i] <= 10^9
Examples
Input: nums = [3, 4, 5, 6]
Output: 0
The parities are already odd, even, odd, even, so no operation is needed.
Input: nums = [4, 8, 12]
Output: 3
All three values are even. Halving 8 three times (8, 4, 2, 1) gives [4, 1, 12], which is even, odd, even. The other pattern, odd, even, odd, needs two halvings of 4 (to 1) and two of 12 (to 3), which is 4 operations.
Input: nums = [5, 7, 2]
Output: 1
5 and 7 are both odd, so at least one operation is needed. Halving 5 once gives [2, 7, 2], which is even, odd, even.