[leetcode] 343. Integer Break

來源:互聯網
上載者:User

標籤:

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     }

 

[leetcode] 343. Integer Break

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.