LeetCode 343. Integer Break 解题报告

来源:互联网 发布:金山数据恢复账号购买 编辑:程序博客网 时间:2024/06/06 03:08

LeetCode 343. Integer Break 解题报告

题目描述

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.


示例

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


限制条件

没有明确给出。


解题思路

我的思路:

这种题目先列一下几个数的情况,找找规律,我列了2-13,如下:

number max 2 1×1=1 3 1×2=2 4 2×2=4 5 2×3=6 6 3×3=9 7 3×4=12 8 3×3×2=18 9 3×3×3=27 10 3×3×4=36 11 3×3×3×2=54 12 3×3×3×3=81 13 3×3×3×4=54

观察上表,可以发现两个规律:
1. 拆分出来的数几乎就只是2,3,4,而不会是5以上的数。因为拆一个5出来,那把5再拆成2跟3就能得到2×3=6更大的乘数,其他6,7,8…类似。
2. 尽可能地拆分3,能获得最大的数。4可以看成是两个2,所以真正考虑拆分出来的基数就只有2跟3,可以通过下列过程证明拆分3能得到更大的数:
假设:x=3m+2n,那么 y=3m×2n=3m×2(x3m)/2
为了方便分析,对y的等式两边取对数:ln(y)=mln3+x3m2ln2=x2ln2+(ln332ln2)m
其中,x一定,(ln332ln2)>0,所以ln(y)是关于m的增函数,也即3的数目(m)越大,y越大。
所以实现的时候,2,3,4这几种情况单独处理,其他情况就是不断地拆分3,直到剩下的数在24之间。


代码

我的代码

class Solution {public:    int integerBreak(int n) {        int result = 1;        if (n <= 4)             return n == 4? 4: n-1;        while (n > 4) {            result *= 3;            n -= 3;        }        return result * n;    }};

总结

这道题挺容易,找找规律就能知道怎么做,没什么好讲的。自己通过了之后参考了liyuanbhu的博文 得知上面的证明过程。
10月2,3日去玩了,所以没有更新博文,接下来几天会补回来的,加油继续填坑!

0 0
原创粉丝点击