343. Integer Break-整数拆分后的多个整数,求最大乘积

版权声明:本文为博主原创文章,转载请说明出处 https://blog.csdn.net/u010002184/article/details/86584718

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.

方法1:

正整数从1开始,但是1不能拆分成两个正整数之和,所以不能当输出。

那么2只能拆成1+1,所以乘积也为1。

数字3可以拆分成2+1或1+1+1,显然第一种拆分方法乘积大为2。

数字4拆成2+2,乘积最大,为4。

数字5拆成3+2,乘积最大,为6。

数字6拆成3+3,乘积最大,为9。

数字7拆为3+4,乘积最大,为12。

数字8拆为3+3+2,乘积最大,为18。

数字9拆为3+3+3,乘积最大,为27。

数字10拆为3+3+4,乘积最大,为36。

....

那么通过观察上面的规律,我们可以看出从5开始,数字都需要先拆出所有的3,一直拆到剩下一个数为2或者4,因为剩4就不用再拆了,拆成两个2和不拆没有意义,而且4不能拆出一个3剩一个1,这样会比拆成2+2的乘积小。那么这样我们就可以写代码了,先预处理n为2和3的情况,然后先将结果res初始化为1,然后当n大于4开始循环,我们结果自乘3,n自减3,根据之前的分析,当跳出循环时,n只能是2或者3或者4,再乘以res返回即可:

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Integer Break.
     *
     * @param n
     * @return
     */
    public int integerBreak(int n) {
        if (n == 2 || n == 3) return n - 1;
        int res = 1;
        while (n > 4) {
            res *= 3;
            n -= 3;
        }
        return res * n;
    }

方法2:

从7开始,差3,则乘3

    /**
     * Runtime: 0 ms, faster than 100.00% of Java online submissions for Integer Break.
     *
     * @param n
     * @return
     */
    public int integerBreak(int n) {
        if (n == 2 || n == 3) return n - 1;
        int[] dp = new int[]{0, 0, 1, 2, 4, 6, 9};
        int res = 1;
        while (n >= 7) {
            res = res * 3;
            n = n - 3;
        }
        return res * dp[n];
    }

参考:http://www.cnblogs.com/grandyang/p/5411919.html

之前一直看的是该题的discuss,看了一个DP的方法,连续4次求最大值,但是看了两天都没看懂,谷歌一搜就看到最通俗的答案!!教训:discuss上并不一定有最佳答案!!

猜你喜欢

转载自blog.csdn.net/u010002184/article/details/86584718