Given two arrays A and B of positive integers of the same size N. The task is to find the maximum sum of products of their elements. Each element in A has to be multiplied with exactly one element in B or vice versa such that each element of both the arrays appears exactly once and the sum of the product obtained is maximum.
Examples:
Input : A[] = {1, 2, 3}, B[] = {4, 5, 1}
Output : 24
Explanation : Maximum sum of product is obtained by 5*3+4*2+1*1 = 24.
Input : A[] = {5, 1, 3, 4, 2}, B[] = {8, 10, 9, 7, 6}
Output : 130
Explanation : Maximum sum of product is obtained by 10*5+9*4+8*3+7*2+6*1 = 130.
The idea is to observe that product of two maximum number will contribute toward the maximum sum of the product. So the idea is to:
- Sort both the arrays.
- Traverse the arrays, and calculate the sum of products of array elements that are at the same index.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
int maximumSOP( int *a, int *b)
{
int sop = 0;
int n = sizeof (a)/ sizeof (a[0]);
sort(a,a+n+1);
sort(b,b+n+1);
for ( int i = 0; i <=n; i++) {
sop += a[i] * b[i];
}
return sop;
}
int main()
{
int A[] = { 1, 2, 3 };
int B[] = { 4, 5, 1 };
cout<<maximumSOP(A, B);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
public class GFG {
static int maximumSOP( int [] a, int [] b)
{
int sop = 0 ;
int n = a.length;
Arrays.sort(a);
Arrays.sort(b);
for ( int i = 0 ; i < n; i++) {
sop += a[i] * b[i];
}
return sop;
}
public static void main(String args[])
{
int [] A = { 1 , 2 , 3 };
int [] B = { 4 , 5 , 1 };
System.out.println(maximumSOP(A, B));
}
}
|
Python 3
def maximumSOP(a, b) :
sop = 0
n = len (a)
a.sort()
b.sort()
for i in range (n) :
sop + = a[i] * b[i]
return sop
if __name__ = = "__main__" :
A = [ 1 , 2 , 3 ]
B = [ 4 , 5 , 1 ]
print (maximumSOP(A, B))
|
C#
using System;
class Program
{
static int MaximumSOP( int [] a, int [] b)
{
int sop = 0;
int n = a.Length;
Array.Sort(a);
Array.Sort(b);
for ( int i = 0; i < n; i++)
{
sop += a[i] * b[i];
}
return sop;
}
static void Main( string [] args)
{
int [] A = { 1, 2, 3 };
int [] B = { 4, 5, 1 };
Console.WriteLine(MaximumSOP(A, B));
}
}
|
PHP
<?php
function maximumSOP(& $a , & $b )
{
$sop = 0;
sort( $a );
sort( $b );
$n = sizeof( $a );
for ( $i = 0; $i < $n ; $i ++)
{
$sop = $sop + ( $a [ $i ] * $b [ $i ]);
}
return $sop ;
}
$A = array (1, 2, 3 );
$B = array (4, 5, 1 );
echo maximumSOP( $A , $B );
?>
|
Javascript
<script>
function maximumSOP(a, b)
{
let sop = 0;
let n = a.length;
a.sort();
b.sort();
for (let i = 0; i <n; i++) {
sop += (a[i] * b[i]);
}
return sop;
}
let A = [ 1, 2, 3 ];
let B = [ 4, 5, 1 ];
document.write(maximumSOP(A, B));
</script>
|
Complexity Analysis:
- Time Complexity: O(nlog(n))
- Auxiliary Space: O(1)