![]() |
VOOZH | about |
Given two arrays of positive integers of size m and n where m > n. We need to maximize the dot product by inserting zeros in the second array but we cannot disturb the order of elements.
Examples:
Input : a[] = [2, 3 , 1, 7, 8] , b[] = [3, 6, 7]
Output : 107
Explanation : We get maximum dot product after inserting 0 at first and third positions in second array.
Maximum Dot Product : = a[i] * b[j]
2*0 + 3*3 + 1*0 + 7*6 + 8*7 = 107Input : a[] = [1, 2, 3, 6, 1, 4], b[] = [4, 5, 1]
Output : 46
Table of Content
The idea is to use Dynamic Programming to find the maximum dot product by selecting elements from array
ain order to match all elements of arrayb. For every pair of indices, there are two choices: either take the current pair and add their product to the previous result, or skip the current element ofa. The DP table stores the maximum dot product possible for different prefixes of the arrays.
(n+1) Ć (m+1)a: dp[iā1][j]dp[n][m]107
In previous approach the current value dp[i][j] is only depend upon the current and previous row values of DP. So to optimize the space complexity we use a single 1D array to store the computations.
107