LN : leetcode 343 Integer Break

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

DP Accepted

dp[i]代表n为i时,和之积的最大值,所以dp[n]即为答案。动态转移方程为dp[i] = max(j*dp[i-j],max(dp[i],j*(i-j))),对于i之前的每一个j都遍历,用j来确定是否就此划分,如果不划分则是dp[i],如果划分则是j*dp[i-j]或j*(i-j),三者取最大值即可。

class Solution {
public:
    int integerBreak(int n) {
        vector<int> dp(n+1, 1);
        for (int i = 3; i <= n; i++) {
            for (int j = 1; j < i; j++) {
                dp[i] = max(j*dp[i-j],max(dp[i],j*(i-j)));
            }
        }
        return dp[n];
    }
};
原文地址:https://www.cnblogs.com/renleimlj/p/7891594.html