Sponsored
Sponsored
This approach involves using dynamic programming to store results of subproblems and avoid redundant calculations.
We define a recursive helper function that considers each element from both arrays and decides whether to include it in the subsequence or not. The dynamic programming table stores the maximum dot product up to the current indices.
Time Complexity: O(m * n) where m and n are the sizes of the two arrays.
Space Complexity: O(m * n) for the dp table.
1def maxDotProduct(nums1, nums2):
2 m, n = len(nums1), len(nums2)
3 dp = [[float('-inf')] * (n + 1) for _ in range(m + 1)]
4 for i in range(1, m + 1):
5 for j in range(1, n + 1):
6 prod = nums1[i - 1] * nums2[j - 1]
7 dp[i][j] = max(dp[i][j], prod)
8 dp[i][j] = max(dp[i][j], prod + dp[i - 1][j - 1] if i > 1 and j > 1 else prod)
9 dp[i][j] = max(dp[i][j], dp[i - 1][j])
10 dp[i][j] = max(dp[i][j], dp[i][j - 1])
11 return dp[m][n]
12
13nums1 = [2, 1, -2, 5]
14nums2 = [3, 0, -6]
15print(maxDotProduct(nums1, nums2))
The Python solution uses a list of lists as a dynamic programming table. It calculates the maximum dot product by iterating and updating the DP table, similar to C and C++ solutions.
This approach involves using backtracking combined with memoization to efficiently enumerate possible subsequences, storing results for reused subsequence comparisons to enhance performance.
The memoization helps to prevent recalculating results for the same indices, transforming exponential time complexity to polynomial time complexity.
Time Complexity: O(m * n) where m and n are the lengths of nums1 and nums2. Although recursive, memoization reduces repeated work.
Space Complexity: O(m * n) for the memoization array.
This C implementation uses a recursive helper function to explore each possible state of subsequences. The dp array is used to cache results of subproblems, reducing the need for redundant calculations.