[LC343] Integer Break

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

这是一道很明显的 dynamic programming 题目,体现在每个数i 的最大乘积可以从 i - j 时的最大数字得来。

举例说 10,可以从6的最大乘积结果9 * 4得来,但是需要注意的是,存在一些数字,i 的最大乘积可能小于等于i,所以在 dynamic programming 的时候需要先行比较 i 和 dp[i]的最大值。

然而这个结果时间复杂度 O(\(n^2)\)

public class Solution {
    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];
    }
}

但是题目存在 O(n)时间复杂度的解法,比较有难度想到。
首先我们思考只需把一个数字拆成两个的最大解,总值为 n,一个数字为 x,那么另外一个数字为(n-x),乘积 (\(x(n - x) = nx - n^2)\),用最简单的微分法得 (\(n - 2x) = 0\) 此时 x = (\(n/2)\) 数字最大。但是 n 是偶数那么(n/2)是最大,如果 n 是奇数,(n-1)/2和 (n+1)/2是最大的结果.

如果想得到 f(x)比 n 大

(N/2)*(N/2)>=N, N>=4

(N-1)/2 *(N+1)/2>=N, N>=5

因此只有所有乘数需要小于4,不然总存在拆分后更好的结果。

所以每次的拆分元素应该是2或者3,因为每次减少1对乘积的扩大毫无帮助

经过实验每次乘积为3能得到较大的结果,这部分没有做详细的数学证明。

public class Solution {
    public int integerBreak(int n) {
        if(n==2) return 1;
        if(n==3) return 2;
        int product = 1;
        while(n>4){
            product*=3;
            n-=3;
        }
        product*=n;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值