343. Integer Break 题解

来源:互联网 发布:微信转换淘宝链接 编辑:程序博客网 时间:2024/06/04 22:33

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

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



题目链接:343. Integer Break



算法描述:


       由题意知,给定一个整数n,将其分解为至少包含两个正整数的各个数之和,我们要求分解得到的整数之积,使其最大化。


        我们寻找分解的规律,当求分解得到的数之积时,2与3的乘积最大,如:2*3 > 1*5; 3*3 > 1*6; 3*2*2 > 1*7; 2*2*2*2 > 1*8 ....... 因此,分解时将原数拆分成多个2 或 3即可。


         当原数n小于或等于3时,直接返回 n-1。否则,我们对其进行拆解,原数n不断减3,结果值ans乘3,直至拆解为小于3的数。如果最后得到的数为0,表示已将其全部拆解为3,直接返回ans。如果最后得到的数为1,我们可以重新组合,将最后两个拆解的数组合为 2*2。如果最后得到的数为2,ans*2 后直接返回。



代码:

class Solution {public:    int integerBreak(int n) {        if(n<=3){            return n-1;        }        int ans =1;        while(n>2){            n -= 3;            ans *= 3;        }        if(n==0){            return ans;        }        if(n==1){            return (ans/3)*4;        }        if(n==2){            return ans*2;        }    }};