-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution1130.java
More file actions
33 lines (31 loc) · 1.1 KB
/
Copy pathSolution1130.java
File metadata and controls
33 lines (31 loc) · 1.1 KB
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
package medium;
public class Solution1130 {
public static void main(String[] args) {
int[][] cases = {
{6, 2, 4},
};
Solution1130 solution = new Solution1130();
for (int[] c : cases)
System.out.println(solution.mctFromLeafValues(c));
}
public int mctFromLeafValues(int[] arr) {
int[][] sum = new int[arr.length][arr.length], max = new int[arr.length][arr.length];
for (int i = 0; i < arr.length; i++) {
int temp = Integer.MIN_VALUE;
for (int j = i; j < arr.length; j++) {
max[i][j] = temp = Math.max(arr[j], temp);
}
}
for (int len = 0; len < arr.length; len++) {
for (int j = len; j < arr.length; j++) {
int i = j - len;
for (int k = i; k < j; k++) {
int temp = sum[i][k] + sum[k + 1][j] + max[i][k] * max[k + 1][j];
if (sum[i][j] == 0 || sum[i][j] > temp)
sum[i][j] = temp;
}
}
}
return sum[0][arr.length - 1];
}
}