Explore

Edit

Edit

# Program to find the maximum scalar product of two vectors | FACE Prep

Published on 10 Mar 2020

Program to find the maximum scalar product of two vectors (dot product) is discussed here. Given two arrays, find the maximum scalar product of all permutations of the two given arrays.

Sample Input 1:

3 (Number of elements of the array)

1 2 3 Array 1 elements)

4 5 6 (Array 2 elements)

Sample Output 1:

32

Calculation:

Maximum scalar product = 1 * 4 + 2 * 5 + 3 * 6

= 4 + 10 + 18

= 32

## Algorithm to find the maximum scalar product of two vectors

• Input the number of elements of the arrays.
• Input the array 1 and array 2 elements.
• Initialize sum = 0.
• Sort the array 1 in descending order.
• Sort the array 2 in descending order.
• Repeat from i = 1 to n
• sum = sum + (arr1[i] * arr2[i])
• Return sum.

## Program to find the maximum scalar product of two vectors (dot product)

C
C++
Java
Python 3

Output
2 (size of each array)
4 (array 1 elements)
5
6 (array 2 elements)
7
59 (maximum scalar product)

## Program to find the maximum scalar product of two vectors (dot product) using pointers

/* C Program to find the maximum scalar product of two vectors (dot product) USING POINTERS*/
#include<stdio.h>
#include<stdlib.h>
int* createarray(int);
int getelements(int*,int);
int ascending(int*,int);
int maxscalar(int*,int*,int);
int i,j;
int main()
{
int n,*a,*b;
scanf(“%d”,&n);
a=createarray(n);
getelements(a,n);
b=createarray(n);
getelements(b,n);
ascending(a,n);
ascending(b,n);
maxscalar(a,b,n);
return 0;
}
int* createarray(int n)
{
int *a;
a=(int*)malloc(n*sizeof(int));
return a;
}
int getelements(int *a,int n)
{
for(i=0;i<n;i++)
scanf(“%d”,(a+i));
return 0;
}
int ascending(int *a,int n)
{
int temp;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(*(a+i)>*(a+j))
{
temp=*(a+i);
*(a+i)=*(a+j);
*(a+j)=temp;
}
}
}
return 0;
}
int maxscalar(int *a,int *b,int n)
{
int p,q,sum=0;
for(i=0;i<n;i++)
{
p=*(a+i);
q=*(b+i);
sum=sum+(p*q);
}
printf(“%d”,sum);
return 0;
}


Recommended Programs