LeetCode #343 - Integer Break - Medium

Problem

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.

Note: You may assume that n is not less than 2 and not larger than 58.

Hint:

  • There is a simple O(n) solution to this problem.
  • You may check the breaking results of n ranging from 7 to 10 to discover the regularities.

Example

given n = 2, return 1 (2 = 1 + 1); given n = 10, return 36 (10 = 3 + 3 + 4).

Algorithm

整理一下题意:给定一个整数n,将n分成至少两个正整数的和,将分成的整数乘起来得到一个积,要求返回积的最大值。假设2<=n<=58。

其实没有明确的思路,所以先尝试枚举。

n最大拆分最大乘积
21+11
31+22
42+24
52+36
63+39
73+412
83+3+218
93+3+327

由上表猜测,最大拆分中需要尽可能多的3。以此为思路,对于n的最大积,通过n每次减3和积每次乘3得到。代码如下。

//时间复杂度O(n)
class Solution {
public:
    int integerBreak(int n) {
        if(n==2) return 1;
        if(n==3) return 2;
        if(n==4) return 4;

        int max=1;
        while(n>4){
            max*=3;
            n-=3;
        }
        return max*n;
    }
};

完成题目后提交,很幸运通过了。但对于其数学原理还是不明白,于是在网上查找资料,发现 @liyuanbhu 老师的博客里有简单的数学证明。下面将这段证明引用如下。感谢 @liyuanbhu 老师的工作!

原文地址:http://blog.csdn.net/liyuanbhu/article/details/51198124
作者:@liyuanbhu


首先证明拆出的因子大于 4 是不行的。设 x 是一个因子,x>4,那么可以将这个因子再拆成两个因子 x−2 和 2,易证 (x−2)×2>x。所以不能有大于 4 的因子。

4 这个因子也是可有可无的,4=2+2,4=2×2。因此 4 这个因子可以用两个 2 代替。

除非没有别的因子可用,1 也不能选作因子。一个数 x 当它大于 3 时,有 (x−2)×2>(x−1)×1。

这样呢,就只剩下 2 和 3 这两个因子可以选了。下面再证明 3 比 2 好。

一个数 x=3m+2n,那么 f=3m×2n=3m×2x−3m2 可以对它取个对数。

lnf===mln3+nln2mln3+x−3m2ln2x2ln2+(ln3−32ln2)m
其中 ln3−32ln2>0 所以 f 是 m 的增函数,也就是说 m 越大越好。所以 3 越多越好。

再多说一句,如果拆出的因子不限于整数的话,可以证明e=2.718… 是最佳的选择。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值