
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Maximum sum of pairwise product in an array with negative allowed in C++
In this tutorial, we will be discussing a program to find maximum sum of pairwise product in an array with negative allowed.
For this we will be provided with an array containing integers. Our task is to find the maximum sum while performing pairwise multiplications.
Example
#include <bits/stdc++.h> #define Mod 1000000007 using namespace std; //finding the maximum sum long long int findSum(int arr[], int n) { long long int sum = 0; //sorting the array sort(arr, arr + n); int i = 0; while (i < n && arr[i] < 0) { if (i != n - 1 && arr[i + 1] <= 0) { sum = (sum + (arr[i] * arr[i + 1]) % Mod) % Mod; i += 2; } else break; } int j = n - 1; while (j >= 0 && arr[j] > 0) { if (j != 0 && arr[j - 1] > 0) { sum = (sum + (arr[j] * arr[j - 1]) % Mod) % Mod; j -= 2; } else break; } if (j > i) sum = (sum + (arr[i] * arr[j]) % Mod) % Mod; else if (i == j) sum = (sum + arr[i]) % Mod; return sum; } int main() { int arr[] = { -1, 9, 4, 5, -4, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findSum(arr, n); return 0; }
Output
87
- Related Articles
- Maximum sum of pairwise product in an array with negative allowed in C++ program
- Maximum product subset of an array in C++
- Find maximum value of Sum( i*arr[i]) with only rotations on given array allowed in C++
- Maximum Product Subarray | Added negative product case in C++
- Return the maximum of an array with negative infinity or maximum ignoring any NaNs in Python
- Maximum product subset of an array in C++ program
- Product of all pairwise consecutive elements in an Arrays in C++
- Maximum sum from a tree with adjacent levels not allowed in C++
- Maximum average sum partition of an array in C++
- Maximum equlibrium sum in an array in C++
- Difference between sum and product of an array in JavaScript
- Find a pair with maximum product in array of Integers in C++
- Ways to sum to N using array elements with repetition allowed in C++
- Absolute Difference of all pairwise consecutive elements in an array (C++)?
- Program to find maximum non negative product in a matrix in Python

Advertisements