Leetcode 343. Integer Break

Posted lettuan

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 343. Integer Break相关的知识,希望对你有一定的参考价值。

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.

 

一个大于3的数拆分的话,可以分成 n*3 + m (m=0,1,2) 这种形式来得到最大的乘积。这里面的例外是m=1的情况,因为这时,把这个1和最后一个3拆分成2+2,可以让product更大。

 1 class Solution(object):
 2     def integerBreak(self, n):
 3         """
 4         :type n: int
 5         :rtype: int
 6         """
 7         if n == 2:
 8             return 1
 9         if n == 3:
10             return 2
11             
12         prod = 1
13         
14         while n >= 3:
15             n -= 3
16             prod = 3*prod
17         
18         if n == 0:
19             return prod
20         elif n == 1:
21             return 4*prod/3
22         elif n == 2:
23             return 2*prod
24             

 

以上是关于Leetcode 343. Integer Break的主要内容,如果未能解决你的问题,请参考以下文章

leetcode [343]Integer Break

[leetcode] 343. Integer Break

leetcode@ [343] Integer Break (Math & Dynamic Programming)

343 Integer Break 整数拆分

LeetCode 343. 整数拆分 | Python

*leetcode 343. 整数拆分 & 剑指offer 14