Please login

Prime

Prepinsta Prime

Video courses for company/skill based Preparation

(Check all courses)
Get Prime Video
Prime

Prepinsta Prime

Purchase mock tests for company/skill building

(Check all mocks)
Get Prime mock

Python Program to Find Maximum Scalar Product of Two Vectors in an Array

Maximum Scalar Product of two Vectors

In this section we learn how to Find Maximum Scalar Product of Two Vectors in an Array using Python.

Scalar product of two vectors is also known as the dot product. Dot product is an algebraic expression which takes two equal sized vectors and returns a single scalar.

Lets say we have two arrays arr1 [1,3,4,2] and arr2 [2,4,3,5] , for finding the maximum scalar product of arrays we need to multiply the minimum value of arr1 to the minimum value of arr2 and add all these multiplied value. So, here we need to sort both the array 1 and array 2 in ascending order i.e.we get arr1 [1,2,3,4] and arr2 [2,3,4,5]

Maximum dot product =  1*2 + 2*3 + 3*4 + 4*5  =  40

Find Maximum Scalar Product of Two Vectors in an Array

Algorithm

  • Step 1 : Inputs from user ( size of array, array 1 elements, array 2 elements )
  • Step 2 : Sorting arr 1 and arr 2 in the ascending order.
  • Step 3 : Call maxScalar(arr1,arr2,n) function and print the result.
maxScalar(arr1,arr2,n):
  1. Initialize a variable sumVariable with value 0 for storing the added values
  2. Traverse each index from 0 to n
  3. Multiply the same index element from arr1 and arr2 and add it to the sumVariable variable.
  4. return sumVariable variable

Python Code

#function to calculate maximum scalar value
def maxScalar(arr1,arr2n):
    sumVariable=0
    for i in range(0,n):
        sumVariable+=arr1[i]*arr2[i]
    return sumVariable

#inputs
n=int(input(“Enter the size of Array: “))
print(“Enter the elements of First Array”)
arr1=list(map(int,input().split()))
print(“Enter the elements of Second Array”)
arr2=list(map(int,input().split()))

#sort arrays in ascending order
arr1.sort()
arr2.sort()

#print maximum scalar value of two arrays
print(“Maximum scalar product of two vectors :”, maxScalar(arr1,arr2,n))

m

Output :

Enter the size of Array: 4
Enter the elements of First Array
1 3 4 2
Enter the elements of Second Array
2 4 3 5
Maximum scalar product of two vectors : 40