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.

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.

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.

假设现在要计算 n = 10,且我们已经知道前面的 n = 2 到 9 的最大拆分乘积。这些信息存在cache数组中。
此时可以取: 1 + 9,此时的乘积是 1 * max ( 9 , cache[ 9 ] ) (可以选择9不拆分了,也可以选择9继续拆分成更小的)
也可以取,     2 + 8,  此时的乘积是 2 * max ( 8, cache [ 8 ] )
也可以取,     3 + 7,  此时的乘积是 3 * max ( 7, cache [ 7 ] )
也可以取,     4 + 6,  此时的乘积是 4 * max ( 6, cache [ 6 ] )
也可以取,     5 + 5,  此时的乘积是 5 * max ( 5, cache [ 5 ] )
也可以取,     6 + 4,  但这个跟 4 + 6重复了。
后面也不需要再计算了。
总结:
for  firstNum = 1...n/2 :
  curMulti = firstNum * max( n - firstNum, cache[  n - firstNum ] )
  curMaxMulti = max (  curMaxMulti, curMulti ) 
cache[ i ] = curMaxMulti

时间复杂度O( n^2 )
空间复杂度O( n )
运行时间:


代码:
public class IntegerBreak {
    public int integerBreak(int n) {
        int[] cache = new int[n + 1];
        cache[2] = 1;
        int i = 3;
        while (i <= n) {
            int max = Integer.MIN_VALUE;
            for (int j = 1; j <= i / 2; j++) {
                max = Math.max(max, j * (Math.max(i - j, cache[i - j])));
            }
            cache[i] = max;
            i++;
        }
        return cache[n];
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值