343.Integer Break

Solution 1: accepted 2ms

DP. The same as the cutting rope issue.
Time: O(n^2)
Space: O(n)

1
2
3
4
5
6
7
8
9
10
11
public int integerBreak(int n) {
if (n < 2) return 0;
int[] dp = new int[n+1];
dp[1] = 1;
for (int i = 2; i <= n; i++) {
for (int j = 1; j < i; j++) {
dp[i] = Math.max(dp[i], j * Math.max(i-j, dp[i-j]));
}
}
return dp[n];
}

Solution 2:

Could use math method.