Skip to content

Commit 13e8601

Browse files
authored
Create Max Dot Product of Two Subsequences.java
1 parent 0c6fe30 commit 13e8601

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
public int maxDotProduct(int[] nums1, int[] nums2) {
3+
int maxOne = Integer.MIN_VALUE;
4+
int maxTwo = Integer.MIN_VALUE;
5+
int minOne = Integer.MAX_VALUE;
6+
int minTwo = Integer.MAX_VALUE;
7+
for (int num : nums1) {
8+
maxOne = Math.max(maxOne, num);
9+
minOne = Math.min(minOne, num);
10+
}
11+
for (int num : nums2) {
12+
maxTwo = Math.max(maxTwo, num);
13+
minTwo = Math.min(minTwo, num);
14+
}
15+
if (maxOne < 0 && minTwo > 0) {
16+
return maxOne * minTwo;
17+
}
18+
if (minOne > 0 && maxTwo < 0) {
19+
return minOne * maxTwo;
20+
}
21+
int[][] dp = new int[nums1.length + 1][nums2.length + 1];
22+
for (int i = nums1.length - 1; i >= 0; i--) {
23+
for (int j = nums2.length - 1; j >= 0; j--) {
24+
int curr = nums1[i] * nums2[j] + dp[i + 1][j + 1];
25+
dp[i][j] = Math.max(curr, Math.max(dp[i + 1][j], dp[i][j + 1]));
26+
}
27+
}
28+
return dp[0][0];
29+
}
30+
}

0 commit comments

Comments
 (0)