您的位置:首页 > 编程语言 > C语言/C++

LeetCode 343. Integer Break 题解(C++)

2016-10-17 20:30 330 查看

LeetCode 343. Integer Break 题解(C++)

题目描述

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).

思路

只要把n尽量多的拆分成3即可。证明如下:

若拆出的因子x大于4,则(x-2)*2>x,即因子x还可以拆分成x-2和2;

若拆出的因子x等于4,则x可以拆成2*2;

若拆出的因子等于1,则(n-1)*1

代码

class Solution
{
public:
int integerBreak(int n)
{
if (n == 2)
{
return 1;
}
if (n == 3)
{
return 2;
}
int product = 1;
while (n > 4)
{
product *= 3;
n -= 3;
}
product *= n;
return product;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode c++