- Arrays, Mathematical

Minimize cost to modify the Array such that even indices have even elements and vice versa

Given an array arr[] of size N and two integers X and Y, the task is to find the minimum cost required to modify the array such that even indices have even elements and odd indices have odd elements on them, either by swapping two elements of the array with a cost of X or by incrementing or decrementing 1 from the element with a cost of Y.Examples: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.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.In case you wish to attend live classes with experts, please refer DSA Live Classes for Working Professionals and Competitive Programming Live for Students.Input: arr[] = {5, 3, 7, 2, 1}, X = 1, Y = 2Output: 5Explanation:Following are the operations performed:Operation 1: Swap the array elements at indices 0 and 3, modifies the array to {2, 3, 7, 5, 1}. The cost of this operations is X(= 1).Operation 2: Incrementing the array elements at index 2, modifies the array to {2, 3, 8, 5, 1}. The cost of this operations is Y(= 2).Operation 3: Incrementing the array elements at index 4, modifies the array to {2, 3, 8, 5, 2}. The cost of this operations is Y(= 2).Therefore, the total cost is 1 + 2 + 2 = 5, which is minimum. Input: arr[] = {1, 2, 3, 4}, X = 1, Y = 2Output: 2Approach: The given problem can be solved by using the following observations by first finding the count of elements that are wrongly placed at odd and even indices as oddCount and evenCount respectively:Case 1: The cost can be calculated by performing the swap operations on a minimum of oddCount and evenCount at a cost of X and performing the decrementing operation on the remaining elements at a cost of Y.Case 2: The cost can be calculated by performing the decrementing operation on the remaining elements at a cost of Y.The minimum of the costs obtained in the above two cases is the required result.Below is the implementation of the above approach:C++  #include using namespace std;  int minimumCost(int arr[], int N,                int X, int Y){            int even_count = 0, odd_count = 0;    for (int i = 0; i < N; i++) {                  if ((arr[i] & 1)            && (i % 2 == 0)) {            odd_count++;        }                  if ((arr[i] % 2) == 0            && (i & 1)) {            even_count++;        }    }                int cost1 = X * min(odd_count, even_count);          int cost2 = Y                * (max(odd_count, even_count)                   - min(odd_count, even_count));                int cost3 = (odd_count + even_count) * Y;              return min(cost1 + cost2, cost3);}  int main(){    int arr[] = { 5, 3, 7, 2, 1 }, X = 10, Y = 2;    int N = sizeof(arr) / sizeof(arr[0]);    cout