forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution1.java
48 lines (35 loc) · 1.07 KB
/
Solution1.java
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
/// Source : https://leetcode.com/problems/integer-break/description/
/// Author : liuyubobobo
/// Time : 2017-11-19
import java.util.Arrays;
/// Memory Search
/// Time Complexity: O(n^2)
/// Space Complexity: O(n)
public class Solution1 {
private int[] memo;
public int integerBreak(int n) {
if(n < 1)
throw new IllegalArgumentException("n should be greater than zero");
memo = new int[n+1];
Arrays.fill(memo, -1);
return breakInteger(n);
}
private int breakInteger(int n){
if(n == 1)
return 1;
if(memo[n] != -1)
return memo[n];
int res = -1;
for(int i = 1 ; i <= n - 1 ; i ++)
res = max3(res, i * (n - i) , i * breakInteger(n - i));
memo[n] = res;
return res;
}
private int max3(int a, int b, int c){
return Math.max(a, Math.max(b, c));
}
public static void main(String[] args) {
System.out.println((new Solution1()).integerBreak(2));
System.out.println((new Solution1()).integerBreak(10));
}
}