首页 > 其他 > 详细

Leetcode 343. Integer Break

时间:2016-11-27 13:47:14      阅读:220      评论:0      收藏:0      [点我收藏+]

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

原文:http://www.cnblogs.com/lettuan/p/6106194.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!