Leetcode 343. Integer Break

时间:2023-12-11 08:20:56

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更大。

 class Solution(object):
def integerBreak(self, n):
"""
:type n: int
:rtype: int
"""
if n == 2:
return 1
if n == 3:
return 2 prod = 1 while n >= 3:
n -= 3
prod = 3*prod if n == 0:
return prod
elif n == 1:
return 4*prod/3
elif n == 2:
return 2*prod