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