标签:product return int Break 因数 ans Integer LeetCode rightarrow
Given an integer n
, break it into the sum of k
positive integers, where \(k\geq 2\), and maximize the product of those integers.
Return the maximum product you can get.
Solution
假设 \(n>4\) 时,且如果存在一个因数 \(f>4\), 那么我们可以换成 \(2,(f-2)\) 这两个因子,因为对于 product:
\[2(f-2) = 2f-4>f \]因此可以发现,对于大于4的因数,可以进行分解。但这并不是最优的,考虑一个例子 \(6\):
\[6 \rightarrow 3*3>2*2*2 \]所以更优的分解是因数 \(3\)。具体来说,求解不等式:
\[3(f-3)\geq f \rightarrow f\ge 5 \]所以当 \(n\ge 5\) 时,分解按照 \(3\) 的最大数量。 但对于 \(4\) 来说,显然最优分解为:
\[4\rightarrow 2*2>3*1 \]点击查看代码
class Solution {
private:
int ans=1;
public:
int integerBreak(int n) {
if(n==2)return 1;
if(n==3)return 2;
if(n==4)return 4;
while(n>4){
ans*=3;n-=3;
}
ans*=n;
return ans;
}
};
标签:product,return,int,Break,因数,ans,Integer,LeetCode,rightarrow 来源: https://www.cnblogs.com/xinyu04/p/16334538.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。