343. Integer Break
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 and not larger than 58.
给定一个正整数,可以将其分割成多个数字的和,若要让这些数字的乘积最大,求分割的方法(至少要分成两个数)。算法返回这个最大的乘积。
可以采用递归的思路,分割n可以拆分为两部分 i 和 n-i分割后获得的最大乘积,递归下去,终止条件是n==1 返回1。
//
//
/// version 1: raw recursion
static int max3(int a, int b, int c) {
return fmax(a, fmax(b, c));
}
static int intbreak(int n) {
if (n <= 2) return 1;
int res = 0;
for (int i = 1; i < n; i++)
res = max3(res, i * (n - i), i * intbreak(n - i));
return res;
}
int integerBreak(int n) {
return intbreak(n);
}
//
//
/// version 2: speed recursion
static int intbreak(int n, int *f){
if (n <= 2) return 1;
if (f[n]) return f[n];
for (int i = 1; i < n; i++)
f[n] = max3(f[n], i * (n - i), i * intbreak(n - i, f));
return f[n];
}
int integerBreak(int n) {
int *f = (int *)calloc(n + 1, sizeof(int));
int res = intbreak(n, f);
free(f);
return res;
}
//
//
/// version 3: iteration
int integerBreak(int n) {
int *f = (int *)calloc(n + 1, sizeof(int));
f[1] = 1;
f[2] = 1;
int res = -1;
for (int i = 3; i <= n; i++) {
for (int j = 1; j < (i / 2) + 1; j++) {
res = max3(res, j * (i - j), j * f[i-j]);
}
f[i] = res;
}
res = f[n];
free(f);
return res;
}