Wednesday, July 3, 2024
HomeData ModellingData Structure & AlgorithmMaximize Array sum after changing sign of any elements for exactly M...

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 = 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>


 
 

Output: 

19

 

 

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

 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

Shaida Kate Naidoo
am passionate about learning the latest technologies available to developers in either a Front End or Back End capacity. I enjoy creating applications that are well designed and responsive, in addition to being user friendly. I thrive in fast paced environments. With a diverse educational and work experience background, I excel at collaborating with teams both local and international. A versatile developer with interests in Software Development and Software Engineering. I consider myself to be adaptable and a self motivated learner. I am interested in new programming technologies, and continuous self improvement.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments