Description
Given two arrays nums1 and nums2.
Return the maximum dot product between non-empty subsequences of nums1 and nums2 with the same length.
A subsequence of an array is a new array which is formed from the original array by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (ie, [2,3,5] is a subsequence of [1,2,3,4,5] while [1,5,3] is not).
Example 1:
Input: nums1 = [2,1,-2,5], nums2 = [3,0,-6] Output: 18 Explanation: Take subsequence [2,-2] from nums1 and subsequence [3,-6] from nums2. Their dot product is (2*3 + (-2)*(-6)) = 18.
Example 2:
Input: nums1 = [3,-2], nums2 = [2,-6,7] Output: 21 Explanation: Take subsequence [3] from nums1 and subsequence [7] from nums2. Their dot product is (3*7) = 21.
Example 3:
Input: nums1 = [-1,-1], nums2 = [1,1] Output: -1 Explanation: Take subsequence [-1] from nums1 and subsequence [1] from nums2. Their dot product is -1.
Constraints:
1 <= nums1.length, nums2.length <= 500-1000 <= nums1[i], nums2[i] <= 1000
Solutions
This function finds the maximum dot product between non-empty subsequences of two arrays using dynamic programming. It builds a 2D table dp where dp[i][j] holds the best dot product achievable using the first i elements of nums1 and the first j elements of nums2, with every cell initialized to -Infinity since at least one pair must be chosen. For each pair of positions, it computes take — the product of the current two numbers, nums1[i - 1] * nums2[j - 1], plus the best previous result dp[i - 1][j - 1] but only if that result is positive (the Math.max(0, ...) lets it start fresh instead of adding a negative total). Each cell then becomes the maximum of take, skipping the current element of nums1 (dp[i - 1][j]), or skipping the current element of nums2 (dp[i][j - 1]). The answer for the full arrays ends up in dp[m][n].
/**
* @param {number[]} nums1
* @param {number[]} nums2
* @return {number}
*/
var maxDotProduct = function (nums1, nums2) {
const m = nums1.length;
const n = nums2.length;
const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(-Infinity));
for (let i = 1; i <= m; i++) {
for (let j = 1; j <= n; j++) {
const take = nums1[i - 1] * nums2[j - 1] + Math.max(0, dp[i - 1][j - 1]);
dp[i][j] = Math.max(take, dp[i - 1][j], dp[i][j - 1]);
}
}
return dp[m][n];
};