Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
For example, given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).
Note: you may assume that n is not less than 2.
Hint:
- There is a simple O(n) solution to this problem.
- You may check the breaking results of n ranging from 7 to 10 to discover the regularities.
假设现在要计算 n = 10,且我们已经知道前面的 n = 2 到 9 的最大拆分乘积。这些信息存在cache数组中。
此时可以取: 1 + 9,此时的乘积是 1 * max ( 9 , cache[ 9 ] ) (可以选择9不拆分了,也可以选择9继续拆分成更小的)
也可以取, 2 + 8, 此时的乘积是 2 * max ( 8, cache [ 8 ] )
也可以取, 3 + 7, 此时的乘积是 3 * max ( 7, cache [ 7 ] )
也可以取, 4 + 6, 此时的乘积是 4 * max ( 6, cache [ 6 ] )
也可以取, 5 + 5, 此时的乘积是 5 * max ( 5, cache [ 5 ] )
也可以取, 6 + 4, 但这个跟 4 + 6重复了。
后面也不需要再计算了。
总结:
for firstNum = 1...n/2 :
curMulti = firstNum * max( n - firstNum, cache[
n - firstNum ] )
curMaxMulti = max (
curMaxMulti, curMulti )
cache[ i ] = curMaxMulti
时间复杂度O( n^2 )
空间复杂度O( n )
运行时间:
代码:
public class IntegerBreak {
public int integerBreak(int n) {
int[] cache = new int[n + 1];
cache[2] = 1;
int i = 3;
while (i <= n) {
int max = Integer.MIN_VALUE;
for (int j = 1; j <= i / 2; j++) {
max = Math.max(max, j * (Math.max(i - j, cache[i - j])));
}
cache[i] = max;
i++;
}
return cache[n];
}
}