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.

开始很自然的想到是DP

class Solution(object):
    def integerBreak(self, n):
        if n <= 3:
            return n-1
        dp = [x for x in range(n+1)]
        for i in range(2,n+1):
            for j in range(2,i+1):
                dp[i] = max(dp[j]*dp[i-j],dp[i])
        return dp[-1]

根据提示找规律:因为3*3>2*2*2, 3*1<2*2

所以根据3的余数处理 注意和上面一样,初始的2和3不适用

class Solution(object):
    def integerBreak(self, n):
        if n <= 3:
            return n-1
        if n%3 == 0:
            return pow(3,n/3)
        if n%3 == 1:
            return pow(3,n/3-1)*4
        if n%3 == 2:
            return pow(3,n/3)*2

 

posted @ 2016-04-27 14:50  lilixu  阅读(125)  评论(0编辑  收藏  举报