Maximum Sum of Products of Two Array in C++ Program

C++Server Side ProgrammingProgramming

In this problem, we are given two arrays arr1[] and arr2[] of size n. Our task is to create a program to find the maximum Sum of Products of Two Array.

Problem Description − We need to find the maximum sum of products of two arrays. We need to find the maximum sum of the product of one element from arr1 and other elements from arr2.

Let’s take an example to understand the problem,

Input

arr1[] = {3, 5, 6} arr2[] = {1, 4, 2}

Output

37

Explanation

Maximum sum of products: 6*4 + 5*2 + 3*1 = 24 + 10 + 3 = 37

Solution Approach

A simple solution to the problem is by finding all pairs of elements from arr1 and arr2. And then return the maximum sum.

An efficient solution to the problem is by multiplying the largest values from both arrays together. An easy way to do this is by sorting the array in descending order. Then multiply all elements for both arrays from index 0 to n and return their sum.

Example

Program to illustrate the working of our solution,

 Live Demo

#include<bits/stdc++.h>
using namespace std;
int calcMaxSumOfProd(int arr1[], int arr2[], int n){
   int maxSum = 0;
   sort(arr1, arr1 + n, greater<int>());
   sort(arr2, arr2 + n, greater<int>());
   for (int i = 0; i < n; i++)
   maxSum += (arr1[i] * arr2[i]);
   return maxSum;
}
int main() {
   int arr1[] = { 3, 5, 6 };
   int arr2[] = { 1, 4, 2 };
   int n = sizeof(arr1)/sizeof(arr1[0]);
   cout<<"The maximum Sum of Products of two arrays is "<<calcMaxSumOfProd(arr1, arr2, n);
   return 0;
}

Output

The maximum Sum of Products of two arrays is 37
raja
Published on 09-Dec-2020 13:31:43
Advertisements