-
Notifications
You must be signed in to change notification settings - Fork 0
/
Maximize dot product
59 lines (44 loc) · 1.39 KB
/
Maximize dot product
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//Maximize dot product
import java.io.*;
import java.util.*;
class GfG {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
while(t-- > 0) {
int n = sc.nextInt();
int m = sc.nextInt();
int a[] = new int[n];
int b[] = new int[m];
for(int i = 0; i < n; i++)
a[i] = sc.nextInt();
for(int i = 0; i < m; i++)
b[i] = sc.nextInt();
Solution ob = new Solution();
System.out.println(ob.maxDotProduct(n, m, a, b));
}
}
}
class Solution {
int help(int i, int j, int n, int m, int a[], int b[], int dp[][], int diff) {
if(i == n || j == m) {
return 0;
}
if(dp[i][j] != -1) {
return dp[i][j];
}
int sum1 = 0, sum2 = 0;
if(diff != 0) {
sum1 = help(i + 1, j, n, m, a, b, dp, diff - 1);
}
sum2 = a[i] * b[j] + help(i + 1, j + 1, n, m, a, b, dp, diff);
return dp[i][j] = Math.max(sum1, sum2);
}
public int maxDotProduct(int n, int m, int a[], int b[]) {
int dp[][] = new int[n][m];
for(int temp[] : dp) {
Arrays.fill(temp, -1);
}
return help(0, 0, n, m, a, b, dp, n - m);
}
}