VOOZH about

URL: https://www.geeksforgeeks.org/dsa/maximum-sum-of-pairwise-product-in-an-array-with-negative-allowed/

⇱ Maximum sum of pairwise product in an array with negative allowed - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum sum of pairwise product in an array with negative allowed

Last Updated : 27 Jul, 2022

Given an array of n elements. Find maximum sum of pairwise multiplications. Sum can be larger so take mod with 10^9+7. If there are odd elements, then we can add any one element (without forming a pair) to the sum.

Examples:

Input : arr[] = {-1, 4, 5, -7, -4, 9, 0}
Output : 77
So to get the maximum sum, the arrangement will 
be {-7, -4}, {-1, 0}, {9, 5} and {4}.
So the answer is (-7*(-4))+((-1)*0)+(9*5)+(4) ={77}.

Input : arr[] = {8, 7, 9}
Output : 79
Answer is (9*8) +(7) = 79.

Approach:

  1. Sort the given array. 
  2. First, multiply the negative numbers pairwise from the starting and add to the total_sum. 
  3. Second, multiply the positive numbers pairwise from the last and to the total_sum. 
  4. Check if negative and positive both counts are odd, then add the product of last pair 
    i.e. last negative and positive left. 
  5. Or if any of the one counts is odd, then add that element left. 
  6. Return sum. 

Implementation:


Output
87

Time Complexity : O(N log(N))
Auxiliary Space: O(1) 

Comment
Article Tags: