Maximizing array sum with given operation in C++


Description

There is an array of (2 * n – 1) integers. We can change sign of exactly n elements in the array. In other words, we can select exactly n array elements, and multiply each of them by -1. Find the maximum sum of the array.

Example

If input array is {-2, 100, -3} then we can obtain maximum changing sign of -2 and -3. After changing sign array becomes −

{2, 100, 3} and maximum sum of this array is 105.

Algorithm

  • Count negative numbers
  • Calculate the sum of the array by taking absolute values of the numbers.
  • Find the minimum number of the array by taking absolute values of the numbers
  • Check if the no. of negative numbers is odd and the value of n is even then subtracting two times m from the sum and this will be maximum sum of the array else, the value of sum will be the maximum sum of the array
  • Repeat above steps (2 * n – 1) times

Example

Let us now see an example −

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMaxSum(int *arr, int n) {
   int negtiveCnt = 0;
   int sum = 0;
   int m = INT_MAX;
   for (int i = 0; i < 2 * n - 1; ++i) {
      if (arr[i] < 0) {
         ++negtiveCnt;
      }
      sum = sum + abs(arr[i]);
      m = min(m, abs(arr[i]));
   }
   if (negtiveCnt % 2 && n % 2 == 0) {
      sum = sum - 2 * m;
      return sum;
   }
   return sum;
}
int main() {
   int arr[] = {-2, 100, -3};
   int n = 2;
   cout << "Maximum sum = " << getMaxSum(arr, n) << endl;
   return 0;
}

Output

Maximum sum = 105

Updated on: 31-Dec-2019

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements