动态规划-343. Integer Break

来源:互联网 发布:爱迪生电弧打火机 淘宝 编辑:程序博客网 时间:2024/06/14 03:30

题目:

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

题意解读:给定一个正整数,把他分裂成至少两个正整数的组合。然后最大化这些正整数的乘积

/*dp[i]代表数i可以分为至少两部分,这些部分的乘积的最大值状态转移方程:dp[i] = Math.max(dp[i],Math.max(dp[i-j],i-j)*Math.max(j,dp[j]));Math.max(dp[i-j],i-j):这里是考虑有些数,无论怎么拆开相乘,还没有数本身大,这种数就不要拆开。比如2,3,4*/class Solution {    public int integerBreak(int n) {        int[] dp = new int[n+1];        // while(++sum <= n){        //     for(int i = 1; i < sum; i++){        //         dp[sum] = Math.max(dp[sum],Math.max(dp[sum-i],sum-i)*Math.max(i,dp[i]));        //     }        // }        //元素可以重复        for(int i = 2; i <= n; i++){            for(int j = 1; j < i; j++)                dp[i] = Math.max(dp[i],Math.max(dp[i-j],i-j)*Math.max(j,dp[j]));        }        return dp[n];    }}



原创粉丝点击