摘要:題目要求將一個(gè)正整數(shù)分解為兩個(gè)或兩個(gè)以上的正整數(shù),要求這些正整數(shù)的乘積最大。思路和代碼這里應(yīng)用了一個(gè)數(shù)學(xué)的思路。假設(shè)我們有一個(gè)數(shù)字,該數(shù)組可以隨機(jī)分解為和。因此取時(shí)可以得到最好的結(jié)果。至于為什么我們需要盡可能用分解,因?yàn)椤?/p>
題目要求
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.
將一個(gè)正整數(shù)分解為兩個(gè)或兩個(gè)以上的正整數(shù),要求這些正整數(shù)的乘積最大。
思路和代碼這里應(yīng)用了一個(gè)數(shù)學(xué)的思路。假設(shè)我們有一個(gè)數(shù)字n,該數(shù)組可以隨機(jī)分解為t和n-t。當(dāng)分解為n/2時(shí)可以獲得最大的乘積。因此t取n/2時(shí)可以得到最好的結(jié)果。但是這里我們明顯還可以繼續(xù)對(duì)t分解(如果t大于1),這樣逐個(gè)分解之后終歸會(huì)分解為2或者1為質(zhì)因數(shù)
假設(shè)N為偶數(shù),(N/2)*(N/2)>=N, 則 N>=4
假設(shè)N為奇數(shù),(N-1)/2 *(N+1)/2, 則 N>=5
因此分解的數(shù)小于4。
至于為什么我們需要盡可能用3分解,因?yàn)?b>3*3>2*2*2。
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; }
想要了解更多開(kāi)發(fā)技術(shù),面試教程以及互聯(lián)網(wǎng)公司內(nèi)推,歡迎關(guān)注我的微信公眾號(hào)!將會(huì)不定期的發(fā)放福利哦~
文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請(qǐng)注明本文地址:http://m.specialneedsforspecialkids.com/yun/68790.html
摘要:思路動(dòng)態(tài)規(guī)劃,前五個(gè)數(shù)的最大乘積為,后面的第個(gè)數(shù)的最大乘積,由從后往前數(shù)包括本身的第三個(gè)數(shù)乘以得到。何睿何睿前個(gè)數(shù)的最大乘積動(dòng)態(tài)規(guī)劃第個(gè)數(shù)的最大乘積為往前數(shù)第三個(gè)數(shù)思路與上面的思路一致,優(yōu)化了空間源代碼文件在這里。 Description Given a positive integer n, break it into the sum of at least two positive...
Problem 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...
Problem A website domain like discuss.leetcode.com consists of various subdomains. At the top level, we have com, at the next level, we have leetcode.com, and at the lowest level, discuss.leetcode.com...
摘要:棧法復(fù)雜度時(shí)間空間思路逆波蘭表達(dá)式的計(jì)算十分方便,對(duì)于運(yùn)算符,其運(yùn)算的兩個(gè)數(shù)就是這個(gè)運(yùn)算符前面的兩個(gè)數(shù)。注意對(duì)于減法,先彈出的是減號(hào)后面的數(shù)。 Evaluate Reverse Polish Notation Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operato...
Problem Implement function atoi to convert a string to an integer. If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values...
閱讀 1325·2021-11-24 09:38
閱讀 3263·2021-11-22 12:03
閱讀 4189·2021-11-11 10:59
閱讀 2327·2021-09-28 09:36
閱讀 1038·2021-09-09 09:32
閱讀 3430·2021-08-05 10:00
閱讀 2538·2021-07-23 15:30
閱讀 2981·2019-08-30 13:12