bigpotato

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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.

Hint:

  1. There is a simple O(n) solution to this problem.
  2. You may check the breaking results of n ranging from 7 to 10 to discover the regularities.

给定一个正整数(取值范围为2~58),将其拆分成至少两个正整数相加,且各拆分出来的数相乘积最大,求所得的最大乘积。

提示:观察7~10的拆分规律。

分析:

  根据提示,我们将n取2~10符合条件的拆分列出如下:

  n    拆分    积

  2    1+1    1*1=1

  3    2+1    2*1=2

  4    2+2    2*2=4

  5    3+2    2*3=6

  6    3+3    3*3=9

  7    3+4    3*4=12

  8    3+3+2       3*3*2=18

  9    3+3+3       3*3*3=27

  10    3+3+4       3*3*4=36

  观察发现,当n>=5时,先拆分k个3,剩余项为2、3、4时乘积最大。原因应该是2、3拆分会变小,4若拆为1+3,乘积也会变小,所以当剩余2、3、4时停止拆分。

代码如下:

int integerBreak(int n)
{
	if (n == 2 || n == 3)
		return n - 1;
	int result = 1;
	while (n > 4)
	{
		result *= 3;
		n -= 3;
	}
	return result*n;
}

  

 

posted on 2018-03-20 14:29  bigpotato  阅读(118)  评论(0)    收藏  举报