题目描述:
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.
将一个数拆分成多个数的和,并使得这些数的乘积最大,求这样的拆分方式。直接遍历各种拆分方式显然不现实,其实可以先从较小的数开始列举一些最有的拆分方法,2=1+1,3=1+2,4=2+2,5=3+2,6=3+3,7=3+2+2,8=3+3+2,9=3+3+3,10=3+3+2+2。可以发现规律,为了扩大乘积,需要尽量拆分出3。
class Solution {
public:
int integerBreak(int n) {
if(n==2) return 1;
else if(n==3) return 2;
int k=n/3;
if(n%3==0) return pow(3,k);
else if(n%3==1) return pow(3,k-1)*4;
else if(n%3==2) return pow(3,k)*2;
}
};
探讨如何将一个正整数拆分为至少两个正整数的和,以使这些数的乘积达到最大值。通过观察和分析,发现拆分出尽可能多的3能够得到最大的乘积。
2495

被折叠的 条评论
为什么被折叠?



