面试题14:剪绳子
题目描述:给你一根长度为n的绳子,请把绳子剪成m段(m,n都是整数,且n>1,m>1),每段绳子的长度记为k[0],k[1],k[2],…,k[m]。请问k[0]k[1]…*k[m]可能的最大乘积是多少?例如,当绳子的长度为8时,我们把它剪成长度分别为2,3,3的三段,此时得到的最大乘积为18。
动态规划
详细代码:
# -*- coding:utf-8 -*-
class Solution:
# 动态规划
def MaxProductAfterCut(self, n):
if n < 2:
return 0
if n == 2:
return 1
if n == 3:
return 2
prodects = [0] * (n + 1)
products[0] = 0
products[1] = 1
products[2] = 2
products[3] = 3
for i in range(4, n + 1):
max = 0
for j in range(1, i//2 + 1):
product = products[j] * products[i - j]
if max < product:
max = product
products[i] = max
return products[n]
贪婪算法
详细代码:
# -*- coding:utf-8 -*-
class Solution:
# 动态规划
def MaxProductAfterCut(self, n):
if n < 2:
return 0
if n == 2:
return 1
if n == 3:
return 2
n_3 = n // 3
if n - (n_3 *3) == 1:
n_3 -= 1
n_2 = (n - n_3 * 3) // 2
return (2 ** n_2) * (3 ** n_3)