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.

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.

题目大意:

一个数字可以分成多个数字的和,求分成多个数字之后得到的最大乘积。

解法:

采用动态规划,使用res[i]记录第i个数字的最大乘积,那么res[i+1]的最大乘积一定是从之前的乘积生成的,所以就有res[i]=Math.max(res[i],Math.max(res[j]*(i-j),j*(i-j)));这种解法的时间复杂度是O(n^2)。

java:

class Solution {
    public int integerBreak(int n) {
        int[] res=new int[n+1];
        res[1]=1;
        for (int i=2;i<=n;i++){
            for (int j=1;j<i;j++){
                res[i]=Math.max(res[i],Math.max(res[j]*(i-j),j*(i-j)));
            }
        }

        return res[n];
    }
}

     还可以采用数学方法来做,通过最后的分析,参考https://www.cnblogs.com/zywscq/p/5415303.html,最佳结果的因子不是2就是3。

class Solution {
    public int integerBreak(int n) {
        if (n==2){
            return 1;
        }else if(n==3){
            return 2;
        }else if (n%3==0){
            return (int) Math.pow(3,n/3);
        }else if (n%3==1){
            return (int) (2*2*Math.pow(3,(n-4)/3));
        }else{
            return (int) (2*Math.pow(3,(n-2)/3));
        }
    }
}

  

猜你喜欢

转载自www.cnblogs.com/xiaobaituyun/p/10919561.html