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.
  • 這題的關鍵是遞歸公式dp[i] = max(dp[i-j]*j,(i-j)*j,dp[i]);
class Solution {
public:
    int integerBreak(int n) {
        vector<int> dp(n+1,1);

        if(n <= 1){
            return 0;
        }

        dp[1] = 1;
        dp[2] = 1;
        for(int i = 3;i <= n;++i){
            for(int j = 2; j < i;++j){
                dp[i] = max(j*(i-j),dp[i]);
                dp[i] = max(j*dp[i-j],dp[i]);
            }
            cout<<dp[i]<<endl;
        }

        return dp[n];
    }
};
發佈了102 篇原創文章 · 獲贊 19 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章