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 <stdio.h>
2#include <limits.h>
3
4int max(int a, int b) {
5 return a > b ? a : b;
6}
7
8int maxDotProduct(int *nums1, int nums1Size, int *nums2, int nums2Size) {
9 int dp[501][501];
10 for (int i = 0; i <= nums1Size; i++) {
11 for (int j = 0; j <= nums2Size; j++) {
12 dp[i][j] = INT_MIN;
13 }
14 }
15 for (int i = 1; i <= nums1Size; i++) {
16 for (int j = 1; j <= nums2Size; j++) {
17 int prod = nums1[i-1] * nums2[j-1];
18 dp[i][j] = max(dp[i][j], prod + (i > 1 && j > 1 ? dp[i-1][j-1] : 0));
19 dp[i][j] = max(dp[i][j], dp[i-1][j]);
20 dp[i][j] = max(dp[i][j], dp[i][j-1]);
21 }
22 }
23 return dp[nums1Size][nums2Size];
24}
25
26int main() {
27 int nums1[] = {2, 1, -2, 5};
28 int nums2[] = {3, 0, -6};
29 int result = maxDotProduct(nums1, 4, nums2, 3);
30 printf("%d\n", result);
31 return 0;
32}
This C implementation uses a 2D array dp
where dp[i][j]
stores the maximum dot product of subsequences up to the i-th index of nums1 and j-th index of nums2.
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 Python version explores indices recursively while storing calculated results in `dp`. The goal in each call is to decide whether to continue down the recursion tree with or without the current element pair.