【动态规划+贪心算法】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,具体证明如下:
在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SL_World

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值