Given an array arr[] consisting of N integers, the task is to find the minimum number of array elements required to be incremented to make the absolute difference between all pairwise consecutive elements even.
Examples:
Input: arr[] = {2, 4, 3, 1, 8}
Output: 2
Explanation:
Operation 1: Incrementing the array element arr[2](= 3) modifies the array to {2, 4, 4, 1, 8}.
Operation 2: Incrementing the array element arr[3](= 1) modifies the array to {2, 4, 4, 2, 8}.
Therefore, the difference between all pairwise adjacent array elements is even.Input: arr[] = {1, 3, 5, 2}
Output: 1
Approach: The given problem can be solved by using the fact that the difference between two numbers is even if and only if both numbers are odd or even. Therefore, the idea is to increment either all the odd or even numbers both numbers are even, and for the minimum count of increment print the minimum of the count of odd numbers or count of even numbers as the result.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the minimum number// of increments of array elements// required to make difference between// all pairwise adjacent elements evenint minOperations(int arr[], int n){ // Stores the count of // odd and even elements int oddcount = 0, evencount = 0; // Traverse the array for (int i = 0; i < n; i++) { // Increment odd count if (arr[i] % 2 == 1) oddcount++; // Increment even count else evencount++; } // Return the minimum number // of operations required return min(oddcount, evencount);} // Driver Codeint main(){ int arr[] = { 2, 4, 3, 1, 8 }; int N = sizeof(arr) / sizeof(arr[0]); cout << minOperations(arr, N); return 0;} |
2
Time Complexity: O(N)
Auxiliary Space: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

