动态规划解法
class Solution:
def integerBreak(self, n: int) -> int:
'''
basecase: dp[0] = dp[1] = 1
state: dp[n]表示拆分正整数n后的乘积最大值
transfer: 当遍历到n时,i可先被拆分为j和i-j
dp[i]由不拆分j和i-j,拆分j和/或i-j等结果的乘积
取其中最大值得来
'''
dp = [0] * (n+1)
dp[0] = dp[1] = 1
for i in range(2, n+1):
for j in range(1, i):
dp[i] = max(dp[i], j*(i-j), j*dp[i-j], dp[j]*(i-j), dp[j]*dp[i-j])
return dp[n]
import math
class Solution:
def integerBreak(self, n: int) -> int:
'''
math.pow()时间复杂度为O(1)
而 ** 和 pow()时间复杂度为O(logn)
'''
if n <= 3:
return n-1
a = n // 3
b = n % 3
if b == 0:
return int(math.pow(3, a))
if b == 1:
return int(math.pow(3, a-1) * math.pow(2, 2))
if b == 2:
return int(math.pow(3, a) * 2)