LeetCode——Integer Break

Question

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.

Solution

动态规划,自底向上求解可以划分方式的最大值,注意要考虑不划分的情况,所以要取两者的最大值。

Code

class Solution {
public:
    int integerBreak(int n) {
        table.resize(60);
        table[1] = 1;
        for (int i = 2; i <= n; i++) {
            table[i] = 1;
            for (int j = 1; j <= i / 2; j++) {
                // 要考虑不划分的情况
                int tmp = max(j, table[j]) * max(i - j, table[i - j]);
                if (tmp > table[i])
                    table[i] = tmp;
            }
        }
        return table[n];
    }
private:
    vector<int> table;    
};
原文地址:https://www.cnblogs.com/zhonghuasong/p/7500626.html