Skip to content

Commit 8677f76

Browse files
committed
Runtime: 0 ms (Top 100.0%) | Memory: 40.80 MB (Top 7.7%)
1 parent 26c4ae7 commit 8677f76

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,26 @@
1+
// Runtime: 0 ms (Top 100.0%) | Memory: 40.80 MB (Top 7.7%)
2+
13
class Solution {
24
public int integerBreak(int n) {
3-
//dp array: maximum product of splitling int i
4-
int[] dp = new int[n + 1];
5-
6-
// traverse
7-
for (int i = 2; i <= n; i++) {
8-
for (int j = 1; j <= i / 2; j++) {
9-
dp[i] = Math.max(Math.max(j * (i - j), j * dp[i - j]), dp[i]);
10-
}
11-
}
12-
return dp[n];
5+
if (n <= 1) {
6+
return 0;
7+
}
8+
int[] memo = new int[n + 1];
9+
return maxProduct(n, memo);
10+
}
11+
12+
private int maxProduct(int n, int[] memo) {
13+
if (n == 2) {
14+
return 1;
15+
}
16+
if (memo[n] != 0) {
17+
return memo[n];
18+
}
19+
int max = 0;
20+
for (int i = 1; i < n; i++) {
21+
max = Math.max(max, Math.max(i * (n - i), i * maxProduct(n - i, memo)));
22+
}
23+
memo[n] = max;
24+
return max;
1325
}
1426
}

0 commit comments

Comments
 (0)