343. Integer Break

50 篇文章 0 订阅
49 篇文章 0 订阅

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];
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值