343. Integer Break

来源:互联网 发布:swatch知乎 编辑:程序博客网 时间:2024/06/06 18:00

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

Note: You may assume that n is not less than 2 and not larger than 58.

Hint:

  1. There is a simple O(n) solution to this problem.
  2. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

两种方案,一个是数学,一个数dp。先说数学方案,把3作为一个参数,具体原因看下面解释:

If an optimal product contains a factor f >= 4, then you can replace it with factors 2 and f-2 without losing optimality, as 2*(f-2) = 2f-4 >= f. So you never need a factor greater than or equal to 4, meaning you only need factors 1, 2 and 3 (and 1 is of course wasteful and you'd only use it for n=2 and n=3, where it's needed).

For the rest I agree, 3*3 is simply better than 2*2*2, so you'd never use 2 more than twice.

代码如下:

public class Solution {    public int integerBreak(int n) {        if (n == 2) {            return 1;        }        if (n == 3) {            return 2;        }        int product = 1;        while (n > 4) {            n = n - 3;            product *= 3;        }        return product * n;    }}
另一种方案是dp,代码如下:

public class Solution {    public int integerBreak(int n) {        /*        0 1        1 1        2 1 * 1 = 1        3 1 * 2 = 2        4 2 * 2 = 4        5 2 * 3 = 6        6 3 * 3 = 9        7 2 * 2 * 3 = 12        8 2 * 3 * 3 = 18        9 3 * 3 * 3 = 27        10 3 * 4 * 3 = 36        */        if (n < 2) {            return n;        }        int[] dp = new int[n + 1];        dp[0] = 0;        dp[1] = 0;        for (int i = 2; i <= n; i ++) {            int j = 1, max = Integer.MIN_VALUE;            while (j < i) {                max = Math.max(max, j * dp[i - j]);                j ++;            }            dp[i] = Math.max(max, i * i / 4);        }        for (int num: dp) {            System.out.println(num);        }        return dp[n];    }}
简化版本如下:

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,dp[j])) * (Math.max(i - j, dp[i - j])));           }       }       return dp[n];}

0 0
原创粉丝点击