Max Dot Product of Two Subsequences

给两个数组, 求两个数组中的同长度的子序列(不是子数组)中最大的dot product.

首先确定dot product是:

通过观察可以看到axbx和ayby是对应的, 并且这题求最值, 所以用dp.

let dp[i][j] = the largest dot product of two arrays start with i and j respectively

dp[0][0] = the largest dot product of two arrays start with 0 and 0, which is the product of first numbers of two arrays.

dp[i][0] (dp[0][j]) is the largest dot product of two arrays start with i and 0 or 0 and j, just find the large product of two numbers.

dp[i][j] is chosen by picking the max of dp[i][j] (do not pick any number of current indexs) and (dp[i-1][j] or dp[i][j-1]) pick one number of each array and nums[i]*nums[j], take current as the max.

class Solution {
public:
    int maxDotProduct(vector<int>& nums1, vector<int>& nums2) {
        vector<vector<int>> dp(nums1.size(), vector<int>(nums2.size(), 0));
        dp[0][0] = nums1[0] * nums2[0];
        for(int i = 1; i < nums1.size(); i++) 
        {
            dp[i][0] = max(dp[i-1][0], nums1[i] * nums2[0]);
        }
        for(int i = 1; i < nums2.size(); i++) 
        {
            dp[0][i] = max(dp[0][i-1], nums1[0] * nums2[i]);
        }
        for(int i = 1; i < nums1.size(); i++)
        {
            for(int j = 1; j < nums2.size(); j++)
            {
                int c = nums1[i] * nums2[j];
                dp[i][j] = max(c,max(dp[i][j-1], max(dp[i-1][j], c+dp[i-1][j-1])));
            }
        }
        return dp[nums1.size()-1][nums2.size()-1];
    }
};