343. Integer Break

343. Integer Break

1. 题目
题目链接

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.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Note: You may assume that n is not less than 2 and not larger than 58.

2. 题目分析
给定正整数,将正整数拆分成多个正整数,找到一种拆分方式,保证拆分后的正整数的乘积最大。

3. 解题思路
看到这个题目,我就想起了剑指offer书上的,一根线段分割成多条线段,找到一种分割方式保证,分割后的线段的乘机最大。明显两题是同样的意思,所以立马有了思路。
即使用贪心算法,将正整数分成多个正整数3,如果余数为1,则将最后一个3取出,让3+1=4,并且把4分成2+2,从而得到的乘积是2*2=4 > 3。
具体为什么,剑指offer中没有解释,当时我也没有理解,只知道这种解决方式,今天参考博客,这
由均值不等式(n个数的算术平均数大于等于它们的几何平均数):
在这里插入图片描述
得:当把输入的n拆分成几个相等的数时它们的积最大。

那么问题来了,拆分成几个呢?

为了方便使用导数,我们先假设我们可以把n拆分成实数。那么设每一个数为x,则一共有n/x个数。

设它们的积为f(x),则f(x)=x(n/x),那么怎么求f(x)最大值呢?求导数!

f′(x)=(n/x2) * x(n/x) * (1-lnx)

当x=e时取极大值。

而我们题目里规定x为整数,那么我们只需要取的x越靠近e越好。那么2<e<3,而且e=2.71828…,所以取3是最好的,如果取不到3就取2。

幂运算复杂度为O(lgn),所以这个算法复杂度为O(lgn)。

4. 代码实现(java)

package com.algorithm.leetcode.dynamicAllocation;

/**
 * Created by 凌 on 2019/1/27.
 * 注释:343. Integer Break
 */
public class IntegerBreak {
    public int integerBreak(int n) {
        if (n <= 1){
            return 0;
        }else if (n == 2){
            return 1;
        }else if (n == 3){
            return 2;
        }

        int max;
        int mod = n%3;//取余
        int temp = n/3;//倍数
        if (mod == 0){
            max = (int)Math.pow(3,temp);
        }else if (mod == 1){
            temp--;
            max = (int)Math.pow(3,temp);
            max *= 4;
        }else{//mod==2
            max = (int)Math.pow(3,temp);
            max *= mod;
        }
        return max;
    }
}

** 5. 动态规划的方法 **
参考博客https://blog.csdn.net/qq_38277085/article/details/80808294
其实该题理解的关键就是,对于一个数来说,我们并不需要考虑它分成2,3,4,…n个的所有情况,我们仅需考虑它被分成两个的情况就可以了。举个例子:
若n=10, 我们仅需要考虑其被拆分为两个数的情况,(1,9) , (2,8), (3,7), (4,6)
对于其中的每个情况,如(4,6),4和6所能被拆分的最大乘积是我们已经在动态规划过程中记录过的。由(1,9) , (2,8), (3,7), (4,6)这四组值乘积的最大值,就可以求出10的最大乘积。
状态转移方程是: dp[i] = Math.max(dp[i] , Math.max(dp[j],j) * Math.max(dp[i-j],(i-j)));

    public int integerBreak(int n) {
        int[]dp = new int[n+1];
        dp[1] = 1;
        dp[2] = 1;
        for (int i = 3; i < n+1; i++) {
            dp[i] = 0;
            //优化,因为不需要遍历到 i-1,拆分i的左右两边是对称的
            for (int j = 1; j <= i/2; j++){
                dp[i] = Math.max(dp[i] , Math.max(dp[j],j) * Math.max(dp[i-j],(i-j)));
            }
           
        }
        return dp[n];
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值