Cut the rope (to prove safety offer_14)

Title Description


The multi-stage cut a rope, and so that each segment of the maximum length product.


n = 2 return 1 (2 = 1 + 1) n = 10 return 36 (10 = 3 + 3 + 4)
 

Greedy
as much as the length of the rope 3 is cut, and does not allow the length of the rope 1 appears. If it does, it has been cut from a good length of rope out in paragraph 3 of the length of the rope 1 regrouping them to cut two lengths of rope 2.
public int integerBreak(int n) {
    if (n < 2)
        return 0;
    if (n == 2)
        return 1;
    if (n == 3)
        return 2;
    int timesOf3 = n / 3;
    if (n - timesOf3 * 3 == 1)
        timesOf3--;
    int timesOf2 = (n - timesOf3 * 3) / 2;
    return (int) (Math.pow(3, timesOf3)) * (int) (Math.pow(2, timesOf2));
}
 

Dynamic Programming

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

 

 


Guess you like

Origin www.cnblogs.com/ziytong/p/12107366.html