Related Articles

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

• Difficulty Level : Basic
• Last Updated : 29 Sep, 2021

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:

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[ ] = {-3, 7, -1, -5, -3}, M = 4
Output: 19
Explanation:
4 operations on the array can be performed as,
Operation 1: Change the sign of arr -> {3, 7, -1, -5, -3}
Operation 2: Change the sign of arr -> {3, 7, 1, -5, -3}
Operation 3: Change the sign of arr -> {3, 7, 1, 5, -3}
Operation 4: Change the sign of arr -> {3, 7, 1, 5, 3}
The maximum sum of array obtained is 19.

Input: arr[ ] = {-4, 2, 3, 1}, M = 3
Output: 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++

 `// C++ program for the above approach``#include ``using` `namespace` `std;` `// Function to find the maximum sum``// with M flips``void` `findMaximumSumWithMflips(``    ``int` `arr[], ``int` `N, ``int` `M)``{` `    ``// Declare a priority queue``    ``// i.e. min heap``    ``priority_queue<``int``, vector<``int``>, greater<``int``> > pq;` `    ``// Declare the sum as zero``    ``int` `sum = 0;` `    ``// Push all elements of the``    ``// array in it``    ``for` `(``int` `i = 0; i < N; i++) {``        ``pq.push(arr[i]);``        ``sum += arr[i];``    ``}` `    ``// Iterate for M times``    ``while` `(M--) {` `        ``// Get the top element``        ``sum -= pq.top();` `        ``// Flip the sign of the``        ``// top element``        ``int` `temp = -1 * pq.top();` `        ``// Remove the top element``        ``pq.pop();` `        ``// Update the sum``        ``sum += temp;` `        ``// Push the temp into``        ``// the queue``        ``pq.push(temp);``    ``}` `    ``cout << sum;``}` `// Driver program``int` `main()``{` `    ``int` `arr[] = { -3, 7, -1, -5, -3 };` `    ``// Size of the array``    ``int` `N = ``sizeof``(arr) / ``sizeof``(arr);``    ``int` `M = 4;` `    ``findMaximumSumWithMflips(arr, N, M);` `    ``return` `0;``}`

## Java

 `// Java implementation of the above approach``import` `java.util.*;``import` `java.lang.*;``import` `java.lang.Math;``class` `GFG {` `// Function to find the maximum sum``// with M flips``static` `void` `findMaximumSumWithMflips(``    ``int` `arr[], ``int` `N, ``int` `M)``{``  ` `    ``// Declare a priority queue``    ``// i.e. min heap``    ``PriorityQueue minHeap = ``new` `PriorityQueue();``  ` `    ``// Declare the sum as zero``    ``int` `sum = ``0``;``  ` `    ``// Push all elements of the``    ``// array in it``    ``for` `(``int` `i = ``0``; i < N; i++) {``        ``minHeap.add(arr[i]);``        ``sum += arr[i];``    ``}``  ` `    ``// Iterate for M times``    ``while` `(M-- >``0``) {``  ` `        ``// Get the top element``        ``sum -= minHeap.peek();``  ` `        ``// Flip the sign of the``        ``// top element``        ``int` `temp = -``1` `* minHeap.peek();``  ` `        ``// Remove the top element``        ``minHeap.remove();``  ` `        ``// Update the sum``        ``sum += temp;``  ` `        ``// Push the temp into``        ``// the queue``        ``minHeap.add(temp);``    ``}``  ` `     ``System.out.println(sum);``}`` ` `    ``// Driver Code``    ``public` `static` `void` `main(String[] args)``    ``{``      ` `        ``// Given input``        ``int` `arr[] = { -``3``, ``7``, -``1``, -``5``, -``3` `};``        ``int` `M = ``4``,N=``5``;``        ``findMaximumSumWithMflips(arr, N, M);``    ` `    ``}``}` `// This code is contributed by dwivediyash`

## Python3

 `# Python 3 program for the above approach` `# Function to find the maximum sum``# with M flips``def` `findMaximumSumWithMflips(arr, N, M):``    ``# Declare a priority queue``    ``# i.e. min heap``    ``pq ``=` `[]` `    ``# Declare the sum as zero``    ``sum` `=` `0` `    ``# Push all elements of the``    ``# array in it``    ``for` `i ``in` `range``(N):``        ``pq.append(arr[i])``        ``sum` `+``=` `arr[i]``        ``pq.sort()` `    ``# Iterate for M times``    ``while` `(M>``0``):``        ``# Get the top element``        ``sum` `-``=` `pq[``0``]` `        ``# Flip the sign of the``        ``# top element``        ``temp ``=` `-``1` `*` `pq[``0``]` `        ``# Remove the top element``        ``pq ``=` `pq[``1``:]` `        ``# Update the sum``        ``sum` `+``=` `temp` `        ``# Push the temp into``        ``# the queue``        ``pq.append(temp)` `        ``pq.sort()``        ``M ``-``=` `1` `    ``print``(``sum``)` `# Driver program``if` `__name__ ``=``=` `'__main__'``:``    ``arr ``=` `[``-``3``, ``7``, ``-``1``, ``-``5``, ``-``3``]` `    ``# Size of the array``    ``N ``=` `len``(arr)``    ``M ``=` `4` `    ``findMaximumSumWithMflips(arr, N, M)``    ` `    ``# This code is contributed by SURENDRA_GANGWAR.`

## C#

 `// C# implementation of the above approach``using` `System;``using` `System.Collections.Generic;``public` `class` `GFG {` `  ``// Function to find the maximum sum``  ``// with M flips``  ``static` `void` `findMaximumSumWithMflips(``int``[] arr, ``int` `N,``                                       ``int` `M)``  ``{` `    ``// Declare a priority queue``    ``// i.e. min heap``    ``List<``int``> minHeap = ``new` `List<``int``>();` `    ``// Declare the sum as zero``    ``int` `sum = 0;` `    ``// Push all elements of the``    ``// array in it``    ``for` `(``int` `i = 0; i < N; i++) {``      ``minHeap.Add(arr[i]);``      ``sum += arr[i];``    ``}``    ``minHeap.Sort();``    ``// Iterate for M times``    ``while` `(M-- > 0) {` `      ``// Get the top element``      ``sum -= minHeap;``      ``// minHeap.RemoveAt(0);` `      ``// Flip the sign of the``      ``// top element``      ``int` `temp = -1 * minHeap;` `      ``// Remove the top element``      ``minHeap.RemoveAt(0);` `      ``// Update the sum``      ``sum += temp;` `      ``// Push the temp into``      ``// the queue``      ``minHeap.Add(temp);``      ``minHeap.Sort();``    ``}` `    ``Console.WriteLine(sum);``  ``}` `  ``// Driver Code``  ``public` `static` `void` `Main(String[] args)``  ``{` `    ``// Given input``    ``int``[] arr = { -3, 7, -1, -5, -3 };``    ``int` `M = 4, N = 5;``    ``findMaximumSumWithMflips(arr, N, M);``  ``}``}` `// This code is contributed by gauravrajput1`

## Javascript

 ``

Output:
`19`

Time Complexity: O(NLogN)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up