题目
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,将它分解成至少2个可能的数并且计算他们的最大乘积
思路分析
这是一个动态规划的题目,对于一个数n,它的分解数最大乘积为max(g(i) * (n - i), i * (n - i)),i从0到n-1,然后取其中的最大值即可
AC代码
class Solution {
public:
int integerBreak(int n) {
int* p = new int[n + 1];
for (int i = 0; i <= n; ++i) p[i] = 0;
p[1] = 0;
p[2] = 1;
for (int i = 3; i <= n; ++i) {
for (int j = 0; j < i; ++j) {
int result = max(p[j] * (i - j), j * (i - j));
p[i] = max(p[i], result);
}
}
return p[n];
}
};