LeetCode 1458. Max Dot Product of Two Subsequences【动态规划】困难

该博客介绍了一种动态规划的解决方案,用于找到两个整数数组中长度相同的非空子序列的最大点积。在给定的C++代码示例中,展示了如何使用动态规划方法来计算这个问题,达到了较高的时间和空间效率。

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) 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

题意:给你两个数组 nums1 和 nums2 。请你返回 nums1nums2 中两个长度相同的 非空 子序列的最大点积。

数组的非空子序列是通过删除原数组中某些元素(可能一个也不删除)后剩余数字组成的序列,但不能改变数字间相对顺序。比方说,[2,3,5] 是 [1,2,3,4,5] 的一个子序列而 [1,5,3] 不是。


解法 动态规划

和LCS差不多的思路,这里分三种情况动态规划:不包含 nums1[i] 、不包含 nums2[j] 、包含 nums1[i], nums2[j](如果之前的最大点积为负数,则需要重新积累)。

class Solution {
public:
    int maxDotProduct(vector<int>& nums1, vector<int>& nums2) {
        int m = nums1.size(), n = nums2.size();
        //dp[i][j]表示nums1[0..i]与nums2[0..j]最大的点积
        vector<vector<int>> dp(m, vector<int>(n, INT_MIN));
        dp[0][0] = nums1[0] * nums2[0];
        //初始状态
        for (int j = 1; j < n; ++j) dp[0][j] = max(dp[0][j - 1], nums1[0] * nums2[j]);
        for (int i = 1; i < m; ++i) dp[i][0] = max(dp[i - 1][0], nums2[0] * nums1[i]);
        //动态规划
        for (int i = 1; i < m; ++i)
            for (int j = 1; j < n; ++j) 
                dp[i][j] = max(max(dp[i - 1][j], dp[i][j - 1]),
                (dp[i - 1][j - 1] > 0 ? dp[i - 1][j - 1] : 0) + nums1[i] * nums2[j]); 
        return dp[m - 1][n - 1];
    }
};

运行效率如下:

执行用时:32 ms, 在所有 C++ 提交中击败了75.80% 的用户
内存消耗:12.7 MB, 在所有 C++ 提交中击败了63.70% 的用户
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

memcpy0

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值