LeetCode: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.

class Solution {
public:
    int integerBreak(int n) {
        if(n == 2)
        return 1;
        vector<int> breakProduct = {1, 2};
        for(int i = 3; i <= n; i ++)
        {
            int maxPro = i - 1;
            int pro1;
            int pro2;
            for(int j = 1; j < i - 1; j ++)
            {
                pro1 = j * breakProduct[i - j - 1];
                if(pro1 > maxPro)
                    maxPro = pro1;
                pro2 = j * (i - j);
                if(pro2 > maxPro)
                    maxPro = pro2;
            }
            breakProduct.push_back(maxPro);
        }
        return breakProduct[n - 1];
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章