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
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.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code