Max Dot Product of Two Subsequences (LeetCode 1458): Solution and Explanation
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
- Let
dp[i][j]be the best dot product using the firstivalues ofnums1and the firstjofnums2, with at least one pair. Fill it with minus infinity. - For each
ifrom 1 to n andjfrom 1 to m, computetake = nums1[i-1] * nums2[j-1] + max(0, dp[i-1][j-1]). - Set
dp[i][j] = max(take, dp[i-1][j], dp[i][j-1]): pair the two values, skipnums1[i-1], or skipnums2[j-1]. - Return
dp[n][m].
Step-by-step example
nums1 = [2,1,-2,5], nums2 = [3,0,-6]
- Row 1 (value 2): dp[1][1] = 2*3 = 6, dp[1][2] = max(0, 6) = 6, dp[1][3] = max(-12, 6) = 6.
- 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.
- Row 3 (value -2): dp[3][1] = 6, dp[3][2] = 6, and dp[3][3] = (-2)*(-6) + dp[2][2] = 12 + 6 = 18.
- 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]1class Solution {
2 public int maxDotProduct(int[] nums1, int[] nums2) {
3 int n = nums1.length, m = nums2.length;
4 final int NEG = Integer.MIN_VALUE / 2;
5 int[][] dp = new int[n + 1][m + 1];
6 for (int[] row : dp) Arrays.fill(row, NEG);
7 for (int i = 1; i <= n; i++) {
8 for (int j = 1; j <= m; j++) {
9 int prod = nums1[i - 1] * nums2[j - 1];
10 int take = prod + Math.max(0, dp[i - 1][j - 1]);
11 dp[i][j] = Math.max(take, Math.max(dp[i - 1][j], dp[i][j - 1]));
12 }
13 }
14 return dp[n][m];
15 }
16}1class Solution {
2public:
3 int maxDotProduct(vector<int>& nums1, vector<int>& nums2) {
4 int n = nums1.size(), m = nums2.size();
5 const int NEG = -(1 << 30);
6 vector<vector<int>> dp(n + 1, vector<int>(m + 1, NEG));
7 for (int i = 1; i <= n; i++) {
8 for (int j = 1; j <= m; j++) {
9 int prod = nums1[i - 1] * nums2[j - 1];
10 int take = prod + max(0, dp[i - 1][j - 1]);
11 dp[i][j] = max(take, max(dp[i - 1][j], dp[i][j - 1]));
12 }
13 }
14 return dp[n][m];
15 }
16};Time and space complexity
O(n * m)
Each of the n * m cells is filled in constant time.
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.