给你两个数组 nums1 和 nums2 。
请你返回 nums1 和 nums2 中两个长度相同的 非空 子序列的最大点积。
数组的非空子序列是通过删除原数组中某些元素(可能一个也不删除)后剩余数字组成的序列,但不能改变数字间相对顺序。比方说,[2,3,5] 是 [1,2,3,4,5] 的一个子序列而 [1,5,3] 不是。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/max-dot-product-of-two-subsequences
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
//状态转移方程
//f[i][j]=max(f[i - 1][j],f[i][j-1],f[i-1][j-1]+nums1[i]*nums2[j],nums1[i]*nums2[j])
//f[i][j]表示nums1(0...i), nums2(0...j)数组最大的点积和。
//f[i - 1][j] 不选择nums1[i], f[i][j-1] 不选择nums2[j]
//注意的是:nums1[i]*nums2[j] 这一项得有,表示就选择nums1[i]和nums2[j]。
class Solution {
public int maxDotProduct(int[] nums1, int[] nums2) {
if (nums1 == null || nums2 == null || nums1.length == 0 || nums2.length == 0) {
return -1;
}
int f[][] = new int[nums1.length][nums2.length];
f[0][0] = nums1[0] * nums2[0];
int max = f[0][0];
for (int i = 0; i < nums2.length; i++) {
int cur = nums1[0] * nums2[i];
if (cur > max) {
max = cur;
}
f[0][i] = max;
}
max = f[0][0];
for (int i = 0; i < nums1.length; i++) {
int cur = nums1[i] * nums2[0];
if (cur > max) {
max = cur;
}
f[i][0] = max;
}
for (int i = 1; i < nums1.length; i++) {
for (int j = 1; j < nums2.length; j++) {
max = nums1[i] * nums2[j];
if (f[i - 1][j] > max) {
max = f[i - 1][j];
}
if (f[i][j - 1] > max) {
max = f[i][j - 1];
}
if ((f[i - 1][j - 1] + nums1[i] * nums2[j]) > max) {
max = f[i - 1][j - 1] + nums1[i] * nums2[j];
}
f[i][j] = max;
}
}
return f[nums1.length - 1][nums2.length - 1];
}
}
12-14
3670
05-27
01-06
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交