Maximize Array sum after changing sign of any elements for exactly M times
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:
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[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 = 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 <bits/stdc++.h>
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[0]);
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<Integer> minHeap = new PriorityQueue<Integer>();
// 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[0];
// minHeap.RemoveAt(0);
// Flip the sign of the
// top element
int temp = -1 * minHeap[0];
// 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
<script>
// Javascript program for the above approach
// Function to find the maximum sum
// with M flips
function findMaximumSumWithMflips(arr, N, M)
{
// Declare a priority queue
// i.e. min heap
let pq = []
// Declare the sum as zero
let sum = 0
// Push all elements of the
// array in it
for(let i = 0; i < N; i++){
pq.push(arr[i])
sum += arr[i]
pq.sort((a, b) => a - b)
}
// 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.shift()
// Update the sum
sum += temp
// Push the temp into
// the queue
pq.push(temp)
pq.sort((a, b) => a - b)
M -= 1
}
document.write(sum)
}
// Driver program
let arr = [-3, 7, -1, -5, -3]
// Size of the array
let N = arr.length
let M = 4
findMaximumSumWithMflips(arr, N, M)
// This code is contributed by gfgking.
</script>
Time Complexity: O(NLogN)
Auxiliary Space: O(N)
Similar Reads
Maximize array sum by alternating the signs of adjacent elements Given an array, arr[] of size N, the task is to find the maximum possible sum of array elements by alternating the signs of adjacent array elements. Examples: Input: arr[] = { -2, 1, 0 } Output: 3 Explanation: Alternating the signs of (arr[0], arr[1]) modifies arr[] to {2, -1, 0}. Alternating the si
7 min read
Find final Array after subtracting maximum from all elements K times Given an array arr[] of N integers and an integer K, the task is to do the below operations with this array K times. Operations are as follows: Find the maximum element (say M) from the array.Now replace every element with M-arri. where 1 ⤠i ⤠N. Examples: Input: N = 6, K = 3, arr[] = {5, 38, 4, 96
9 min read
Maximize array product by changing any array element arr[i] to (-1)*arr[i] - 1 any number of times Given an array arr[] consisting of N integers, the task is to modify the array elements by changing each array element arr[i] to (-1)*arr[i] - 1 any number of times such that the product of the array is maximized. Examples: Input: arr[] = {-3, 0, 1}Output: 2 -1 -2Explanation:Performing the following
7 min read
Maximize total set bits of elements in N sized Array with sum M Given two integers N and M denoting the size of an array and the sum of the elements of the array, the task is to find the maximum possible count of total set bits of all the elements of the array such that the sum of the elements is M. Examples: Input: N = 1, M = 15Output: 4Explanation: Since N =1,
8 min read
Maximize sum of odd-indexed array elements by repeatedly selecting at most 2*M array elements from the beginning Given an array arr[] consisting of N integers and an integer M (initially 1), the task is to find the maximum sum of array elements chosen by Player A when two players A and B plays the game optimally according to the following rules: Player A starts the game.At every chance, X number of elements ca
15+ min read