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.
将一个正整数分解为两个或两个以上的正整数,要求这些正整数的乘积最大。面试
这里应用了一个数学的思路。假设咱们有一个数字n,该数组能够随机分解为t和n-t。当分解为n/2时能够得到最大的乘积。所以t取n/2时能够获得最好的结果。可是这里咱们明显还能够继续对t分解(若是t大于1),这样逐个分解以后终归会分解为2或者1为质因数数组
假设N为偶数,(N/2)*(N/2)>=N, 则 N>=4
假设N为奇数,(N-1)/2 *(N+1)/2, 则 N>=5微信
所以分解的数小于4。less
至于为何咱们须要尽量用3分解,由于3*3>2*2*2
。spa
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; }
想要了解更多开发技术,面试教程以及互联网公司内推,欢迎关注个人微信公众号!将会不按期的发放福利哦~code