Maximum sum of pairwise product in an array with negative allowed in C++ program

C++Server Side ProgrammingProgramming

In this problem, we are given an array arr[] that contains n integers values (negative values allowed). Our task is to create a program to find the maximum sum of pairwise products in an array with negative allowed.

Problem Description − We need to create pairs using the elements of the array such that the sum of the product of elements of pairs is maximum.

Let’s take an example to understand the problem,

Input

arr[] = {−5, 2, 3, 7, −1, 1, −3, 12}

Output

104

Explanation

The pairs to be considered: (−5, −3), (2, 3), (−1, 1), (7, 12)
Sum of product = (−5 * −3) + (2 * 3) + (−1 * 1) + (7 * 12) = 15 + 6 − 1 + 84 =
104.

Solution Approach

To solve the problem, we will be finding pairs in such a way that the sum of their products is maximum. To maximize the sum, we need to pair the same pair values together. And making this pairing easy, we need to sort the array and then pair up negatives and positives. Then find if one positive or negative or both values are present in the pair. If a positive/negative value is remaining add it to the pair and if one negative and one positive are present then add their product.

Algorithm

Initialize

maxSum = 0.

Step 1

Sort the array arr[].

Step 2

Loop for all negative values of the array. Make pairs, and add their
product to maxSum.

Step 3

Loop for all positive values of the array. Make pairs, and add their
product to maxSum.

Step 4

At last check the remaining values.

Step 4.1

If one positive value remains, add it to maxSum.

Step 4.1

If one negative value remains, add it to maxSum.

Step 4.1

If one positive value and one negative value remains, add
their product to maxSum.

Step 5

Return maxSum.

Example

Program to illustrate the working of our solution,

 Live Demo

#include <bits/stdc++.h>
using namespace std;
long calcSumPairProd(int arr[], int n) {
   long maxSum = 0;
   sort(arr, arr + n);
   int i = 0, j = (n − 1);
   while (i < n && arr[i] < 0) {
      if (i != n − 1 && arr[i + 1] <= 0) {
         maxSum = (maxSum + (arr[i] * arr[i + 1]) );
         i += 2;
      }
      else
      break;
   }
   while (j >= 0 && arr[j] > 0) {
      if (j != 0 && arr[j − 1] > 0) {
         maxSum = (maxSum + (arr[j] * arr[j − 1]) );
         j −= 2;
      }
      else
      break;
   }
   if (j > i)
   maxSum = (maxSum + (arr[i] * arr[j]) );
   else if (i == j)
   maxSum = (maxSum + arr[i]);
   return maxSum;
}
int main() {
   int arr[] = { −5, 2, 3, 7, −1, 1, −3, 12 };
   int n = sizeof(arr) / sizeof(arr[0]);
   cout<<"The maximum sum of pairwise product in an array is "<<calcSumPairProd(arr, n);
   return 0;
}

Output

The maximum sum of pairwise product in an array is 104
raja
Published on 09-Dec-2020 17:56:34
Advertisements