标签:
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.
Solution:
if n = 2, 2 = 1 + 1, f(2) = 1
if n = 3, 3 = 1 + 2, f(3) = 2
if n = 4, 4 = 2 + 2, f(4) = 4
if n > 4, n = (n - 3) + 3, 3*(n-3) > n, 因此所有大于4的整数,都可以通过拆分成2, 3, 4的组合来达到最大值。
其中,4又等价于2 + 2, 所以只需要使用2和3两个数。
下面证明n>4时,需要将n拆分成尽可能多的3.
for n > 4, n = 2 * x + 3 * y (x>=0, y >= 0)
f(n) = 2^x * 3^y = 2^((n - 3y)/2) * 3^y
lnf(n) = yln3 + (n - 3y)/2 * ln2 = n/2 *ln2 + (ln3 - 3/2 * ln2)y
let g(y) = n/2 *ln2 + (ln3 - 3/2 * ln2)y
显然,g(y)是y的增函数,所以y越大越好,即:3的个数越多越好
非递归解:
1 int integerBreak(int n) 2 { 3 if (n < 4) 4 return n - 1; 5 if (n == 4) 6 return 4; 7 8 int ret = 1; 9 while (n > 4) 10 { 11 ret *= 3; 12 n -= 3; 13 } 14 15 return ret * n; 16 }
递归解:
1 int integerBreak(int n) 2 { 3 if (n < 4) 4 return n - 1; 5 else if (n == 4) 6 return 4; 7 else if (n - 3 < 4) 8 return (n - 3) * 3; 9 10 return integerBreak(n - 3) * 3; 11 }
标签:
原文地址:http://www.cnblogs.com/ym65536/p/5539251.html