算法设计作业9

来源:互联网 发布:霍建华演技知乎 编辑:程序博客网 时间:2024/05/21 16:23

第九周作业:

343. Integer Break


解题思路:


343. Integer Break

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.718. 取每个因子为3,但是因此不应出现1,因为出现了3*1<2*2;所以当最后的因子拆分到剩下4的时候,我们应该将4拆成2*2.或者直接就当做4(4=2*2)。

代码如下:
class Solution {public:int integerBreak(int n) {int result = 1;if (n == 2)result = 1;else if (n == 3)result = 2;else {while (n > 4) {result *= 3;n -= 3;}result *= n;}return result;}};


0 0
原创粉丝点击