|
2 | 2 |
|
3 | 3 | // #Medium #Dynamic_Programming #Math
|
4 | 4 |
|
5 | | -import java.util.HashMap; |
6 | | -import java.util.Map; |
7 | | - |
8 | 5 | public class Solution {
|
9 | | - private finalMap<Integer, Integer> memo = newHashMap<>(); |
| 6 | + private int[] arr; |
10 | 7 |
|
11 | 8 | public int integerBreak(int n) {
|
12 | | - if (memo.containsKey(n)) { |
13 | | - return memo.get(n); |
14 | | - } |
15 | | - if (n == 2) { |
16 | | - return 1; |
17 | | - } |
18 | | - int ans = 0; |
19 | | - for (int i = 1; i <= n / 2; i++) { |
20 | | - int ret = integerBreak(n - i); |
21 | | - int product = Math.max(i * (n - i), i * ret); |
22 | | - ans = Math.max(ans, product); |
| 9 | + arr = new int[n + 1]; |
| 10 | + arr[2] = 1; |
| 11 | + // only case involve with 1 other than 2 is 3 |
| 12 | + return n == 3 ? 2 : dp(n); |
| 13 | + } |
| 14 | + |
| 15 | + private int dp(int n) { |
| 16 | + if (n <= 2) { |
| 17 | + return arr[2]; |
| 18 | + } else if (arr[n] != 0) { |
| 19 | + return arr[n]; |
| 20 | + } else { |
| 21 | + int prod = 1; |
| 22 | + for (int i = 2; i <= n; i++) { |
| 23 | + prod = Math.max(prod, i * dp(n - i)); |
| 24 | + } |
| 25 | + arr[n] = prod; |
23 | 26 | }
|
24 | | - memo.put(n, ans); |
25 | | - return ans; |
| 27 | + return arr[n]; |
26 | 28 | }
|
27 | 29 | }
|
0 commit comments