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.
1function maxDotProduct(nums1, nums2) {
2 const m = nums1.length, n = nums2.length;
3 const dp = Array.from({ length: m + 1 }, () => Array(n + 1).fill(-Infinity));
4 for (let i = 1; i <= m; i++) {
5 for (let j = 1; j <= n; j++) {
6 const prod = nums1[i - 1] * nums2[j - 1];
7 dp[i][j] = Math.max(dp[i][j], prod);
8 dp[i][j] = Math.max(dp[i][j], prod + (i > 1 && j > 1 ? dp[i - 1][j - 1] : 0));
9 dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]);
10 dp[i][j] = Math.max(dp[i][j], dp[i][j - 1]);
11 }
12 }
13 return dp[m][n];
14}
15
16const nums1 = [2, 1, -2, 5];
17const nums2 = [3, 0, -6];
18console.log(maxDotProduct(nums1, nums2));
The JavaScript solution creates and manipulates a 2D array to compute the maximum dot product. It follows the same logic pattern as the C and Python solutions, filling in potential max products step by step.
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.