Description
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.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Note: You may assume that n is not less than 2 and not larger than 58.
分析
题目的意思是:把一个数分解为几个数,然后使得几个数之积最大。
- 是一个找规律的题目,我们来看一下:
正整数从1开始,但是1不能拆分成两个正整数之和,所以不能当输出。
2只能拆成1+1,所以乘积也为1。
数字3可以拆分成2+1或1+1+1,显然第一种拆分方法乘积大为2。
数字4拆成2+2,乘积最大,为4。
数字5拆成3+2,乘积最大,为6。
数字6拆成3+3,乘积最大,为9。
数字7拆为3+4,乘积最大,为12。
数字8拆为3+3+2,乘积最大,为18。
数字9拆为3+3+3,乘积最大,为27。
数字10拆为3+3+4,乘积最大,为36。
- 我们可以看出从5开始,数字都需要先拆出所有的3,一直拆到剩下一个数为2或者4,因为剩4就不用再拆了,拆成两个2和不拆没有意义,而且4不能拆出一个3剩一个1,这样会比拆成2+2的乘积小。
C++实现
class Solution {
public:
int integerBreak(int n) {
if (n == 2 || n == 3) return n - 1;
int res=1;
while(n>4){
res=res*3;
n=n-3;
}
return res*n;
}
};
Python实现
这道题要找规律,如果找不到规律,就只能dp。
当i>=2的时候,可以拆分成至少两个正整数的和,设第一个是x,第二个是n-x,n-x可以继续进行拆分,或者不进行拆分。
dp[i]表示将正整数 i拆分成至少两个正整数的和之后,这些正整数的最大乘积。
- 将i拆分成i-j和j,i-j不继续拆分,则乘积是j*(i-j)
- 将i拆分成j,i-j后继续拆分,则乘积是j*dp[i-j]
因此:
dp[i]=max(dp[i],j*dp[i-j],j*(i-j))
class Solution:
def integerBreak(self, n: int) -> int:
dp = [0]*(n+1)
for i in range(2,n+1):
for j in range(i):
dp[i]=max(dp[i],j*dp[i-j],j*(i-j))
return dp[n]