Minimum Operations to Make Array Parity Alternating Problem
Description
LeetCode Problem 3854.
You are given an integer array nums.
An array is called parity alternating if for every index i where 0 <= i < n - 1, nums[i] and nums[i + 1] have different parity (one is even and the other is odd).
In one operation, you may choose any index i and either increase nums[i] by 1 or decrease nums[i] by 1.
Return an integer array answer of length 2 where:
answer[0]is the minimum number of operations required to make the array parity alternating.answer[1]is the minimum possible value ofmax(nums) - min(nums)taken over all arrays that are parity alternating and can be obtained by performing exactlyanswer[0]operations.
An array of length 1 is considered parity alternating.
Example 1:
Input: nums = [-2,-3,1,4]
Output: [2,6]
Explanation:
Applying the following operations:
- Increase nums[2] by 1, resulting in nums = [-2, -3, 2, 4].
- Decrease nums[3] by 1, resulting in nums = [-2, -3, 2, 3].
The resulting array is parity alternating, and the value of max(nums) - min(nums) = 3 - (-3) = 6 is the minimum possible among all parity alternating arrays obtainable using exactly 2 operations.
Example 2:
Input: nums = [0,2,-2]
Output: [1,3]
Explanation:
Applying the following operation:
- Decrease nums[1] by 1, resulting in nums = [0, 1, -2].
The resulting array is parity alternating, and the value of max(nums) - min(nums) = 1 - (-2) = 3 is the minimum possible among all parity alternating arrays obtainable using exactly 1 operation.
Example 3:
Input: nums = [7]
Output: [0,0]
Explanation:
No operations are required. The array is already parity alternating, and the value of max(nums) - min(nums) = 7 - 7 = 0, which is the minimum possible.
Constraints:
1 <= nums.length <= 10^5-10^9 <= nums[i] <= 10^9
Solution
Approach: Greedy
The final array has one of two shapes: even numbers on even indices and odd numbers on odd indices, or the other way round. For each shape, count the elements with the wrong parity; each needs one operation (change it by 1).
To keep the gap between the maximum and the minimum small, a wrong-parity element equal to the global minimum is raised by 1 and one equal to the global maximum is lowered by 1; other elements can go either way without affecting the extremes. Then record the new minimum and maximum (the gap is at least 1). Pick the shape with fewer operations, and on a tie the one with the smaller gap.
Complexity: O(n) time and O(1) extra space.
from math import inf
class Solution:
def makeParityAlternating(self, nums: List[int]) -> List[int]:
def f(k: int) -> List[int]:
cnt = 0
a, b = inf, -inf
for i, x in enumerate(nums):
if ((x - i) & 1) != k:
cnt += 1
if x == mn:
x += 1
elif x == mx:
x -= 1
a = min(a, x)
b = max(b, x)
return [cnt, max(1, b - a)]
if len(nums) == 1:
return [0, 0]
mn, mx = min(nums), max(nums)
return min(f(0), f(1))