- Arrays, Greedy

Maximize Array sum after changing sign of any elements for exactly M times

Given an array arr[] of size N and an integer M, the task is to find the maximum sum of the array after changing the sign of any elements in the array for exactly M times. It is allowed to change the sign of the same element multiple times.Examples:Input: arr[ ] = {-3, 7, -1, -5, -3}, M = 4Output: 19Explanation:4 operations on the array can be performed as,Operation 1: Change the sign of arr[0] -> {3, 7, -1, -5, -3}Operation 2: Change the sign of arr[2] -> {3, 7, 1, -5, -3}Operation 3: Change the sign of arr[3] -> {3, 7, 1, 5, -3}Operation 4: Change the sign of arr[4] -> {3, 7, 1, 5, 3}The maximum sum of array obtained is 19.Input: arr[ ] = {-4, 2, 3, 1}, M = 3Output: 10   Approach: To solve the problem, the main idea is to flip the smallest number of the array in each iteration. By doing so, the negative values will be changed to positive and the array sum will be maximized.Follow the steps below to solve the problem:Initialize a min priority queue, say pq[], and push all the elements of the array arr[].Initialize a variable, say sum = 0, to store the maximum sum of the array.Iterate a while loop till M  is greater than 0 and do the following:Pop from the priority queue and subtract it from the variable sum.Flip the sign of the popped element by multiplying it with -1 and add it to the sum.Push the new flipped element in the priority queue and subtract 1 from M.Finally, print the maximum sum stored in the variable sum.Below is the implementation of the above approach:C++#include using namespace std;  void findMaximumSumWithMflips(    int arr[], int N, int M){              priority_queue pq;          int sum = 0;              for (int i = 0; i < N; i++) {        pq.push(arr[i]);        sum += arr[i];    }          while (M--) {                  sum -= pq.top();                          int temp = -1 * pq.top();                  pq.pop();                  sum += temp;                          pq.push(temp);    }      cout