Problem Description
Given two arrays nums1 and nums2, find the maximum dot product between non-empty subsequences (of equal length) selected from each array. A subsequence is formed by deleting some (or no) elements without reordering the remaining elements. Special care is needed when arrays contain all negative numbers.
Key Insights
- The goal is to maximize the dot product between aligned elements of two subsequences.
- Use dynamic programming to consider all pairs (i, j) where subsequences ending at nums1[i] and nums2[j] can be formed.
- It is crucial to consider starting a new subsequence at (i, j) with just the product or extending an existing subsequence.
- Skipping an element in one array could lead to a better result, so carry over the best value from previous states.
- Handle negative values carefully since the product may be negative, and a "restart" might be beneficial.
Space and Time Complexity
Time Complexity: O(n * m), where n and m are the lengths of nums1 and nums2. Space Complexity: O(n * m) due to the dp table used to store the maximum dot products.
Solution
We construct a dp table where dp[i][j] represents the maximum dot product possible using any subsequences ending at index i in nums1 and index j in nums2. For each dp[i][j]:
- Compute the current product = nums1[i] * nums2[j].
- Option 1: Start a new subsequence with this product.
- Option 2: Extend a previously computed subsequence from dp[i-1][j-1] by adding the current product.
- Also consider the best result from dp[i-1][j] (skipping nums1[i]) and dp[i][j-1] (skipping nums2[j]). The final answer resides in dp[n-1][m-1].