Making Array Parity Alternating

You have an array of integers and want to make it alternate between even and odd numbers. To fix a number's parity, you can either add 1 or subtract 1 (costing 1 operation). You want to achieve this alternating pattern using the lowest possible number of operations.

Among all the ways to do this optimally, find the sequence that yields the smallest difference between its largest and smallest numbers. Return the minimum operations and that minimum range difference.

Example 1:

Input: nums = [4, 4, 4]

Output: [1, 1]

Explanation: We can make the array parity alternating by targeting an "even, odd, even" pattern. This requires exactly 1 operation: modifying the middle element nums[1] from an even 4 to an odd number. We can either increase it to 5 (creating [4, 5, 4]) or decrease it to 3 (creating [4, 3, 4]). In both of these optimal scenarios, the minimum operations required is 1, and the resulting max(nums) - min(nums) is 1.

Example 2:

Input: nums = [10, 2, 10]

Output: [1, 7]

Explanation: To achieve an "even, odd, even" pattern, we only need to perform 1 operation to make nums[1] odd. We have two choices for changing the 2: increase it to 3 or decrease it to 1. If we decrease it, the resulting array is [10, 1, 10], which has a max-min difference of 9. To minimize this difference, we should strategically increase it to 3 instead. The resulting array is [10, 3, 10], yielding an optimal minimum difference of 10 - 3 = 7.

Now Your Turn!

Pick the correct output for the given input

Input: nums = [1, 3, 5, 7]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= nums.length <= 105
  • -109 <= nums[i] <= 109

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
class Solution {
public:
vector<int> minOperations(vector<int>& nums) {
// Write your code here
}
};
Test Case

Input:

Nums