Max Dot Product of Two Subsequences (LeetCode 1458): Solution and Explanation

Hard
Array
Dynamic Programming

Pick a non-empty subsequence from each array, both of the same length, and pair them up in order. Return the largest possible sum of the pairwise products.

Intuition

Choosing two equal-length subsequences in order is the same as drawing non-crossing lines between the arrays, exactly as in Longest Common Subsequence. The only difference is what a line is worth: the product of its two ends.

So look at the last values nums1[i-1] and nums2[j-1]. Either they are paired with each other, or at least one of them is unused and can be dropped.

If they are paired, the earlier part is optional. A positive earlier total helps; a negative one is better thrown away, which is why the pair adds max(0, previous best).

The catch is that at least one pair is required. Starting the table at minus infinity rather than 0 means no cell can claim an empty answer.

Approach: 2D DP over prefixes

  1. Let dp[i][j] be the best dot product using the first i values of nums1 and the first j of nums2, with at least one pair. Fill it with minus infinity.
  2. For each i from 1 to n and j from 1 to m, compute take = nums1[i-1] * nums2[j-1] + max(0, dp[i-1][j-1]).
  3. Set dp[i][j] = max(take, dp[i-1][j], dp[i][j-1]): pair the two values, skip nums1[i-1], or skip nums2[j-1].
  4. Return dp[n][m].

Step-by-step example

nums1 = [2,1,-2,5], nums2 = [3,0,-6]
  1. Row 1 (value 2): dp[1][1] = 2*3 = 6, dp[1][2] = max(0, 6) = 6, dp[1][3] = max(-12, 6) = 6.
  2. Row 2 (value 1): dp[2][1] = max(3, 6) = 6, dp[2][2] = max(0 + 6, 6, 6) = 6, dp[2][3] = max(-6 + 6, 6, 6) = 6.
  3. Row 3 (value -2): dp[3][1] = 6, dp[3][2] = 6, and dp[3][3] = (-2)*(-6) + dp[2][2] = 12 + 6 = 18.
  4. Row 4 (value 5) cannot beat 18, so dp[4][3] = 18: pairs 2*3 and (-2)*(-6).

Code: Python, Java, C++

1class Solution:
2    def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
3        n, m = len(nums1), len(nums2)
4        NEG = float('-inf')
5        dp = [[NEG] * (m + 1) for _ in range(n + 1)]
6        for i in range(1, n + 1):
7            for j in range(1, m + 1):
8                prod = nums1[i - 1] * nums2[j - 1]
9                take = prod + max(0, dp[i - 1][j - 1])
10                dp[i][j] = max(take, dp[i - 1][j], dp[i][j - 1])
11        return dp[n][m]
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n * m)

Each of the n * m cells is filled in constant time.

Space

O(n * m)

The full table is stored. Keeping only the previous row reduces it to O(m).

Other approaches

Rolling one-row DP (time O(n * m), space O(m))

Each row depends only on the row above and the cell to its left, so two arrays of length m + 1 are enough.

Shortcut for the all-negative case (time O(n * m), space O(n * m))

If every product is negative (one array all positive, the other all negative), the answer is the single pair with the smallest absolute product, max(nums1) * min(nums2) or the reverse. Otherwise run the DP initialised to 0. It works but the minus-infinity version handles everything in one pass.

Common mistakes

  • Initialising dp with 0. That allows the empty subsequence, so [-1,-1] and [1,1] would return 0 instead of -1.
  • Writing take = prod + dp[i-1][j-1] without the max(0, ...). With minus infinity in the table that would wipe out every first pair.
  • Using Integer.MIN_VALUE as minus infinity in Java or C++ and then adding to it. Use MIN_VALUE / 2 or guard the addition, since max(0, ...) already keeps it out of the sum here.
  • Forgetting the skip options. The best pairs are often far apart, so dp[i-1][j] and dp[i][j-1] must carry earlier answers forward.

Frequently asked questions

Why max(0, dp[i-1][j-1]) instead of just dp[i-1][j-1]?

The pair (i-1, j-1) can either extend an earlier selection or be the first pair on its own. Starting fresh is worth exactly the product, so if the earlier best is negative or still minus infinity, it is better ignored.

Can the answer be negative?

Yes. When one array is all negative and the other all positive, every product is negative and at least one pair is required, so the answer is the least negative single product.

How is this related to Uncrossed Lines?

Uncrossed Lines counts non-crossing equal-value lines and uses the same three-way recurrence. Here each line has a weight, the product, and the empty selection is not allowed.