VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-maximum-dot-product-two-arrays-insertion-0s/

⇱ Maximum dot product of two arrays with insertion of 0's - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Maximum dot product of two arrays with insertion of 0's

Last Updated : 26 May, 2026

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 = 107

Input : a[] = [1, 2, 3, 6, 1, 4], b[] = [4, 5, 1]
Output : 46

[Naive Approach] Using 2D Dynamic Programming - O(m Ɨ n) Time and O(m Ɨ n) Space

The idea is to use Dynamic Programming to find the maximum dot product by selecting elements from array a in order to match all elements of array b. 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 of a. The DP table stores the maximum dot product possible for different prefixes of the arrays.

  • Create a DP table of size (n+1) Ɨ (m+1)
  • Traverse both arrays: Take current pair: a[iāˆ’1]Ɨb[jāˆ’1]+dp[iāˆ’1][jāˆ’1]a[i-1]. Skip current from a: dp[iāˆ’1][j]
  • Store the maximum of both choices
  • Final answer is stored in dp[n][m]

Output
107

[Optimized Approach] Using 1D Dynamic Programming - O(m Ɨ n) Time and O(n) Space

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.

  • Create an array dp to store the maximum dot product values.
  • Initialize all elements of dp to 0.
  • Iterate over the a array and process each element.
  • For each element in a, iterate over the b array in reverse order and process each element.
  • Update dp[j] with the maximum value between the current dp[j] and dp[j - 1] + (a[i - 1] * b[j - 1]).
  • After the loops, dp[n] will represent the maximum dot product achievable.
  • Return dp[n] as the result.

Output
107
Comment
Article Tags: