#1458
Max Dot Product of Two Subsequences
HardArrayDynamic ProgrammingDynamic ProgrammingArray
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n * m) |
| Space | O(1) | O(n * m) |
💡
Intuition
Time O(n * m)Space O(n * m)
The optimal solution uses dynamic programming to build a table that captures the maximum dot product for subsequences of different lengths. This avoids the need to generate all subsequences explicitly, leading to a more efficient solution.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a DP table where DP[i][j] represents the maximum dot product of subsequences ending at nums1[i-1] and nums2[j-1].
- 2Step 2: Iterate through each element of nums1 and nums2, updating the DP table based on previous values and the current elements.
- 3Step 3: Return the maximum value found in the DP table.
solution.py7 lines
1def maxDotProduct(nums1, nums2):
2 n, m = len(nums1), len(nums2)
3 dp = [[float('-inf')] * (m + 1) for _ in range(n + 1)]
4 for i in range(1, n + 1):
5 for j in range(1, m + 1):
6 dp[i][j] = max(dp[i-1][j-1] + nums1[i-1] * nums2[j-1], nums1[i-1] * nums2[j-1], dp[i][j])
7 return max(max(row) for row in dp)ℹ
Complexity note: The complexity is O(n * m) because we fill a DP table of size n x m, where n and m are the lengths of the two input arrays.
- 1Subsequences can be tricky; focus on lengths and positions.
- 2Dynamic programming can significantly reduce complexity.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.