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).
Two methods to solve it: backtracking and DP
#include <iostream>
#include <vector>
using namespace std;
// backtracking.
void integerBreak(int n, int& target, int& multiply, int& maxMultiply) {
if(target > n) return;
if(target == n) {
maxMultiply = max(maxMultiply, multiply);
return;
}
for(int i = 1; i < n; ++i) {
target += i;
multiply *= i;
integerBreak(n, target, multiply, maxMultiply);
target -= i;
multiply /= i;
}
}
int integerBreak(int n) {
int target = 0;
int multiply = 1;
int maxMultiply = 1;
integerBreak(n, target, multiply, maxMultiply);
return maxMultiply;
}
// DP
int integerBreakII(int n) {
vector<int> mults(n + 1, 0);
mults[1] = 1;
mults[2] = 2;
for(int i = 2; i <= n; ++i) {
for(int j = 1; j < i; ++j) {
mults[i] = max(mults[i], max(mults[j], j) * max(mults[i - j], i - j));
}
}
return mults[n];
}
int main(void) {
int maxValue = integerBreakII(10);
cout << maxValue << endl;
}
本文介绍了一种算法问题:将正整数拆分为至少两个正整数之和并最大化这些整数的乘积。提供了两种解决方案:回溯法和动态规划法,并通过C++代码实现。
1722

被折叠的 条评论
为什么被折叠?



