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