本文最后更新于:2022年4月9日 中午
给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。
示例 1:
| 输入: 2 输出: 1 解释: 2 = 1 + 1, 1 × 1 = 1。
|
示例 2:
| 输入: 10 输出: 36 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
|
说明: 你可以假设 n 不小于 2 且不大于 58。
Solution
参考 @liuyubobobo 、**@LeetCode官方**

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| class Solution { private: int dfs(int n){ if(n==1) return n; int res = -1; for(int i=1; i<=n-1; ++i){ res = max(res, max(i*(n-i), i*dfs(n-i))); } return res; } public: int integerBreak(int n) { return dfs(n); } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { private: vector<int> memo;
int dfs(int n){ if(n==1) return 1; if(memo[n] != -1) return memo[n];
int res = -1; for(int i=1; i<=n-1; ++i){ res = max(res, max(i*(n-i), i*dfs(n-i))); } memo[n] = res; return res; } public: int integerBreak(int n) { memo = vector<int>(n+1, -1); return dfs(n); } };
|
| class Solution { public: int integerBreak(int n) { vector<int> dp(n+1, -1); dp[1] = 1; for(int i=2; i<=n; ++i){ for(int j=1; j<=i-1; ++j){ dp[i] = max(dp[i], max(j*(i-j), j*dp[i-j])); } } return dp[n]; } };
|