Max Dot Product of Two Subsequences - Problem

Given two arrays nums1 and nums2, find the maximum dot product between non-empty subsequences of the same length.

The dot product of two sequences is the sum of products of corresponding elements. For example, the dot product of [2, 3] and [1, 4] is 2×1 + 3×4 = 14.

A subsequence is formed by deleting some (possibly zero) elements from the original array while maintaining the relative order. For instance, [2, 5] is a valid subsequence of [1, 2, 3, 5], but [5, 2] is not.

Goal: Return the maximum possible dot product between equal-length subsequences from both arrays.

Input & Output

example_1.py — Basic Case
$ Input: nums1 = [2,1,-2,5], nums2 = [3,0,-1]
Output: 15
💡 Note: Take subsequence [5] from nums1 and [3] from nums2. Dot product = 5 × 3 = 15, which is the maximum possible.
example_2.py — Multiple Elements
$ Input: nums1 = [3,-2], nums2 = [2,-6,7]
Output: 21
💡 Note: Take subsequence [3,-2] from nums1 and [2,7] from nums2 (skipping -6). Dot product = 3×2 + (-2)×7 = 6 - 14 = -8. Wait, better choice: take [3] and [7] for 3×7 = 21.
example_3.py — All Negative
$ Input: nums1 = [-1,-1], nums2 = [-1,-1]
Output: 1
💡 Note: When all numbers are negative, the best strategy is to take the single largest (least negative) element from each array: (-1) × (-1) = 1.

Constraints

  • 1 ≤ nums1.length, nums2.length ≤ 500
  • -1000 ≤ nums1[i], nums2[i] ≤ 1000
  • Both subsequences must be non-empty
  • Subsequences must have the same length

Visualization

Tap to expand
Max Dot Product of Two Subsequences INPUT nums1 array: 2 1 -2 5 i=0 i=1 i=2 i=3 nums2 array: 3 0 -1 j=0 j=1 j=2 nums1 = [2, 1, -2, 5] nums2 = [3, 0, -1] Find max dot product Subsequences maintain relative order Example: [2,5] from nums1 ALGORITHM STEPS 1 Create DP Table dp[i][j] = max dot product using nums1[0..i], nums2[0..j] 2 Base Case dp[0][0] = nums1[0]*nums2[0] = 2 * 3 = 6 3 Recurrence dp[i][j] = max of: - dp[i-1][j-1] + a[i]*b[j] - dp[i-1][j], dp[i][j-1] - nums1[i] * nums2[j] 4 Compute Answer Best pair: [5] and [3] 5 * 3 = 15 DP Table (partial) j: 0 1 2 i=0: 6 6 6 i=3: 15 15 15 FINAL RESULT Optimal Subsequences: From nums1: 2 1 -2 5 From nums2: 3 0 -1 Dot Product Calculation: 5 x 3 = 15 Output: 15 OK Key Insight: Dynamic Programming handles negative numbers by tracking the maximum achievable dot product at each position. We can either include current pair (nums1[i] * nums2[j]) or skip elements from either array. Starting fresh with just nums1[i]*nums2[j] helps when all previous products are negative. TutorialsPoint - Max Dot Product of Two Subsequences | Optimal Solution
Asked in
Google 28 Amazon 22 Microsoft 18 Apple 15
29.1K Views
Medium Frequency
~25 min Avg. Time
1.2K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen