ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
# 剪绳子 1. 动态规划。先从最低处开始计算乘积并将每个数可以剪切后得到的成绩最大值进行存储。当计算后面的值的时候利用已经存储好的最大值,计算所有可能的结果并保留最大的。时间复杂度O(n\*n)空间复杂度O(n) 2. 贪心算法 ``` // 动态规划 function maxProductAfterCutting(length) { if (length < 2) { return 0 } if (length === 2) { return 1 } if (length === 3) { return 2 } let product = [0, 1, 2, 3] for (let i = 4; i <= length; i++) { let max = 0 for (let j = 1; j <= i / 2; j++) { let current = product[j] * product[i - j] if (max < current) { max = current } } product[i] = max } return product } ``` ``` // 贪心算法 function maxProductAfterCutting(length) { if (length < 2) { return 0 } if (length === 2) { return 1 } if (length === 3) { return 2 } let threeCounts = Math.floor(length / 3) if (length - 3 * threeCounts === 1) { threeCounts-- } let lessLength = length - 3 * threeCounts let twoCounts = Math.floor(lessLength / 2) return Math.pow(3, threeCounts) * Math.pow(2, twoCounts) } ```