Integer Break
LeetCode上的343题:https://leetcode.com/problems/integer-break/
文章目录
题目
给定一个正整数n,将其分解为至少两个正整数的和,并最大化这些整数的乘积。返回能得到的最大乘积。
Example1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example1:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
题解
将i分解为至少两个正整数的和,令P(i)为这些整数的最大乘积。则P(i)可以分解为:P(i) = max(P(j)*(i-j)) i = 1, …i-1。由于对称性j只需遍历到i/2
代码
class Solution {
public:
int integerBreak(int n) {
if (n <= 2) return 1;
vector<int> num(n, 0);
num[0] = num[1] = 1;
for (int i = 3; i <= n; i++)
for (int j = 1; j <= i / 2; j++)
num[i-1] = max(num[i-1], max(j*num[i-j-1], j*(i-j)));
return num[n-1];
}
};