Integer Break问题及解法

来源:互联网 发布:cleanmymac3破解版mac 编辑:程序博客网 时间:2024/05/22 16:06

问题描述:

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.

示例:

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.

问题分析:

通过分析发现对于n来说,它的最大乘积dp[n] 是 dp[i] * (n - i) 或 i * (n - i) 中最大的那个, (1<= i <= n - 1).


过程详见代码:

class Solution {public:    int integerBreak(int n) {        vector<int> dp(n + 1, 1);for (int i = 2; i <= n; i++){for (int j = 1; j < i; j++)dp[i] = max(dp[i],max(dp[j] * (i - j), j * (i - j)));}return dp[n];    }};


原创粉丝点击