Created
January 8, 2026 20:24
-
-
Save tatsuyax25/e4efd6ba5e262eb49b029e51f0ee1032 to your computer and use it in GitHub Desktop.
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 a array is a new array which is formed from the original array by deleting some (can be none)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * @param {number[]} nums1 | |
| * @param {number[]} nums2 | |
| * @return {number} | |
| */ | |
| var maxDotProduct = function(nums1, nums2) { | |
| const m = nums1.length; | |
| const n = nums2.length; | |
| // Create a DP table where: | |
| // dp[i][j] = max dot product using nums1[0..i-1] and nums2[0..j-1] | |
| // | |
| // We initialize everything to -Infinity because: | |
| // - We want to allow negative numbers. | |
| // - We want to ensure that taking no elements is never considered valid. | |
| const dp = Array.from({ length: m + 1 }, () => | |
| Array(n + 1).fill(-Infinity) | |
| ); | |
| // Fill the DP table | |
| for (let i = 1; i <= m; i++) { | |
| for (let j = 1; j <= n; j++) { | |
| const product = nums1[i - 1] * nums2[j - 1]; | |
| dp[i][j] = Math.max( | |
| product, // Start a new subsequence with this pair | |
| dp[i - 1][j - 1] + product, // Extend previous subsequence | |
| dp[i][j - 1], // Skip nums2[j - 1] | |
| dp[i - 1][j] // Skip nums1[i - 1] | |
| ); | |
| } | |
| } | |
| return dp[m][n]; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment