leetcode-面试题14-1-剪绳子

题目描述:

leetcode-面试题14-1-剪绳子_第1张图片

 

 第一次提交:

class Solution:
    def cuttingRope(self, n: int) -> int:
        ans = 0
        for m in range(2,max(n//2,3)):
            j = 1
            a = n//m
            b = n%m
            for _ in range(b):
                j *= (a+1)
            for _ in range(m-b):
                j *= (a)
            ans = max(ans,j)
        return ans

数学法:O(1)

class Solution:
    def cuttingRope(self, n: int) -> int:
        if n <= 3: return n - 1
        a,b = n//3,n%3
        if b == 0: return int(math.pow(3,a))
        if b == 1:return int(math.pow(3,a-1)*4)
        return int(math.pow(3,a)*2)

 

你可能感兴趣的:(leetcode-面试题14-1-剪绳子)