343. Integer Break(unsolved)

来源:互联网 发布:混沌一键瞬狙数据逆战 编辑:程序博客网 时间:2024/05/16 10:43

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).

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

解答:由常识,可知,假如把一个数拆违两部分,那么平均分后,
(N/2)(N/2)是乘积最大的分法。但是要求是整数,所以对于奇数而言,要分为(N+1)/2 (N-1)/2,
令这两条式子大于等于N,那么
N>=4, 和N>=5
所以,所有区分的因子都要小于4,否则都可以分为N/2。
所以因子可以为1,2,3。
1肯定不行了,那么考虑2,3。
由于4=2+2=1+3,6=2+2+2=3+3
所以,4和以下的结果为4,4以上的尽量用3,即尽量取因子3

class Solution {public:    int integerBreak(int n) {        if(n==2) return 1;        if(n==3) return 2;        int result=1;        while(n>4)        {            n-=3;            result*=3;        }        if(n!=0) result*=n;        return result;    }};
0 0
原创粉丝点击