# Find Maximum dot product of two arrays with insertion of 0's in C++

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

Suppose we have two arrays of positive integers of size m and n. The m > n. We have to maximize the dot product by inserting zeros in the second array. One thing we have to keep in mind that we will not change the ordering of the elements in the given arrays. Suppose the arrays are A = [2, 3, 1, 7, 8], and another array B = [3, 6, 7]. The output will be 107. We can maximize the dot product after inserting 0s at first and third position of the second array. So the product will be 2 * 0 + 3 * 3 + 1 * 0 + 7 * 6 + 8 * 7 = 107.

To solve this, we will use the Dynamic programming approach. So the size of A is m, and size of B is n. We will create one table for dynamic programming of the order (n + 1)x(m + 1), and fill it with 0s. Now use these steps to do the rest −

• For i in range 1 to n:

• For j := i to m

• For j := i to m

• table[i, j] := max(table[i - 1, j - 1] + A[j - 1] * B[i - 1], table[i, j - 1])

## Example

Live Demo

#include <iostream>
using namespace std;
long long int findMaximumDotProd(int A[], int B[], int m, int n) {
long long int table[n+1][m+1];
for(int i = 0; i<=n; i++){
for(int j = 0; j<=m; j++){
table[i][j] = 0;
}
}
for (int i=1; i<=n; i++)
for (int j=i; j<=m; j++)
table[i][j] = max((table[i-1][j-1] + (A[j-1]*B[i-1])) , table[i][j-1]);
return table[n][m] ;
}
int main() {
int A[] = { 2, 3 , 1, 7, 8 } ;
int B[] = { 3, 6, 7 } ;
int m = sizeof(A)/sizeof(A[0]);
int n = sizeof(B)/sizeof(B[0]);
cout << "Maximum dot product: " << findMaximumDotProd(A, B, m, n);
}

### Output

Maximum dot product: 107
Updated on 03-Jan-2020 10:34:38