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.

public class Solution {

    public int integerBreak1(int n) {
    if (n <= 2) return 1;
    if (n == 3) return 2;
    if (n == 4) return 4;
    int[] dp = new int[n+1];
    dp[2] = 2;
    dp[3] = 3;
    dp[4] = 4;
    for (int i = 5; i <= n; ++i) {
        dp[i] = 3 * dp[i-3];
    }
    return dp[n];
    }


    public int integerBreak(int n) {
        int[] dp=new int[n+1];
        dp[0]=1;
        dp[1]=1;

        for(int i=2;i<=n;i++){
            for(int j=1;2*j<=i;j++)
                dp[i]=Math.max(dp[i],(Math.max(j,dp[j])) * (Math.max(i - j, dp[i - j])));
        }

        return dp[n];
    }
}

results matching ""

    No results matching ""