【动态规划+贪心算法】Maximum Product(剪绳子 or 整数拆分)

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

原题地址:

UOJ#41
Leetcode 343:整数拆分

一、动态规划解法

#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,具体证明如下:
在这里插入图片描述
在这里插入图片描述

发布了126 篇原创文章 · 获赞 438 · 访问量 25万+

猜你喜欢

转载自blog.csdn.net/SL_World/article/details/103321832