Leetcode 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 and not larger than 58.

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

题意就是讲一个整数分为若干个数(至少两个),使得这若干个数的乘积最大。利用动态规划不难求解,对于数n ,状态转移方程如下,复杂度o(n^2):

for(i=1 to n-1)
求出max{i*dp(n-i)}即可
//这里需要注意的是n<4时,要另外考虑
class Solution {
public:
    int integerBreak(int n) {
        vector<int> array(n);
        array[0] = 1;
        array[1] = 1;
        array[2] = 2;
        if (n == 1||n==2) {
            return 1;
        }
        if (n == 3) {
            return 2;
        }
        int max,temp;
        for (int i = 4; i <= n; i++) {
            max = 0;
            for (int j = 1; j < i ; j++) {
                if (i - j < 4) {
                    temp = i - j;
                }
                else {
                    temp = array[i - j - 1];
                }
                if (j*temp > max) {
                    max = j*temp;
                }
            }
            array[i - 1] = max;
        }
        return array[n - 1];
    }
};

但是有一个更优的解法时间复杂度为o(n),注意到:其实分解因子的时候每个因子都不会大于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;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值