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.
1import java.util.*;
2
3class Solution {
4 public int maxDotProduct(int[] nums1, int[] nums2) {
5 int m = nums1.length, n = nums2.length;
6 int[][] dp = new int[m + 1][n + 1];
7 for (int[] row : dp) Arrays.fill(row, Integer.MIN_VALUE);
8 for (int i = 1; i <= m; i++) {
9 for (int j = 1; j <= n; j++) {
10 int prod = nums1[i - 1] * nums2[j - 1];
11 dp[i][j] = Math.max(dp[i][j], prod);
12 dp[i][j] = Math.max(dp[i][j], prod + (i > 1 && j > 1 ? dp[i - 1][j - 1] : 0));
13 dp[i][j] = Math.max(dp[i][j], dp[i - 1][j]);
14 dp[i][j] = Math.max(dp[i][j], dp[i][j - 1]);
15 }
16 }
17 return dp[m][n];
18 }
19
20 public static void main(String[] args) {
21 Solution sol = new Solution();
22 int[] nums1 = {2, 1, -2, 5};
23 int[] nums2 = {3, 0, -6};
24 System.out.println(sol.maxDotProduct(nums1, nums2));
25 }
26}
This Java solution involves a two-dimensional array dp
. It adapts the same methodology to calculate the maximum dot product by iterating through both arrays and considering subsequences at each 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.