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
📈 Investment Portfolio Matching StrategyPeriod 1 Stocks: [2, 1, -2, 5]$2Stock A$1Stock B-$2Stock C$5Stock DPeriod 2 Stocks: [3, 0, -1]$3Stock X$0Stock Y-$1Stock ZDynamic Programming DecisionsStartTakeSkip1Skip2Memoization preventsrecalculating subproblemsOptimal: Stock D + Stock X = $5 × $3 = $15🎯 Optimal Portfolio StrategyStock D: $5×Stock X: $3=Profit: $15← Maximum possible return!Time Complexity: O(m×n) | Space: O(m×n) memoization tableEach stock pair position (i,j) is evaluated exactly once and stored for future reference
Understanding the Visualization
1
Evaluate Each Position
At each stock pair, decide: buy both, skip first period, or skip second period
2
Calculate Profit
If buying both stocks, multiply their values (dot product)
3
Explore All Combinations
Use memoization to efficiently try all valid portfolio combinations
4
Find Maximum
Return the portfolio combination with the highest total value
Key Takeaway
🎯 Key Insight: Use dynamic programming to systematically explore all portfolio combinations while avoiding redundant calculations through memoization, achieving optimal O(m×n) performance.
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