Description
Given a rope whose length is n(1<=n<=501<=n<=50), please cut the rope to m parts to get the maximum product of the length of each part ∏l1+l2+…+lm=nl1∗l2∗…∗lm∏l1+l2+…+lm=nl1∗l2∗…∗lm. For example, if a rope with length 8, when we cut it to 2, 3, 3, we can get the maximum product 18.
Sample Input
8
Sample Output
18
原题地址:
一、动态规划解法
#include <iostream>
#include <cstring>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;
/**
* Maximum Product 贪心纸质版作业第3题之剪绳子,使得每段乘积最大;力扣343
* (1<=n<=50)
*/
class Solution {
public:
// 动态规划
int DP_maxProduct(int len) {
if(len <= 3)
return len;
int opt[len + 1];
opt[2] = 2;
opt[3] = 3;
for(int i = 4;i <= len;i++){
max_product = 0;
for(int j = 2;j <= (i/2);j++){
product = opt[i - j] * j;
if(product > max_product)
max_product = product;
}
opt[i] = max_product;
}
return opt[len];
}
private:
int max_product, product;
};
int main(){
int len;
cin >> len;
Solution sol;
cout<<sol.DP_maxProduct(len)<<endl;
return 0;
}
二、贪心解法
#include <iostream>
#include <cstring>
#include <math.h>
#include <vector>
#include <algorithm>
using namespace std;
class Solution {
public:
int Greedy_maxProduct(int len) {
if(len <= 4)
return len;
// 对f(n)=(L/n)^n求导等于0后,得到m=(L/e),e取整为3,取该划分份数时函数乘积最大
numOf3 = len / 3;
if (len % 3 == 0)
return pow(3, numOf3);
else if(len % 3 == 1)
return pow(3, numOf3 - 1) * 4;
else
return pow(3, numOf3) * 2;
}
private:
int numOf3;
};
int main(){
int len;
cin >> len;
Solution sol;
cout<<sol.Greedy_maxProduct(len)<<endl;
return 0;
}
对于为什么划分因子是2和3,具体证明如下: