首页 > 代码库 > Leetcode 343. Integer Break
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。