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.
1#include <iostream>
2#include <vector>
3#include <algorithm>
4using namespace std;
5
6int maxDotProduct(vector<int>& nums1, vector<int>& nums2) {
7 int m = nums1.size(), n = nums2.size();
8 vector<vector<int>> dp(m + 1, vector<int>(n + 1, INT_MIN));
9 for (int i = 1; i <= m; i++) {
10 for (int j = 1; j <= n; j++) {
11 int prod = nums1[i - 1] * nums2[j - 1];
12 dp[i][j] = max(dp[i][j], prod);
13 dp[i][j] = max(dp[i][j], prod + (i > 1 && j > 1 ? dp[i - 1][j - 1] : 0));
14 dp[i][j] = max(dp[i][j], dp[i - 1][j]);
15 dp[i][j] = max(dp[i][j], dp[i][j - 1]);
16 }
17 }
18 return dp[m][n];
19}
20
21int main() {
22 vector<int> nums1 = {2, 1, -2, 5};
23 vector<int> nums2 = {3, 0, -6};
24 cout << maxDotProduct(nums1, nums2) << endl;
25 return 0;
26}
In this C++ solution, a two-dimensional vector dp
is used similar to the C solution. The algorithm involves iterating through the indices of both arrays to compute the maximum possible dot product subsequences.
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.