剑指OFFER----14、剪绳子(js实现)

题目

给你一根长度为n的绳子,请把绳子剪成m段(m , n )都是正整数,(n>1&m>1)

每段绳子的长度为k[0],k[1],k[2],…,k[m]。请问k[0]k[1]k[2]…k[m]的最大值。

例如绳子是长度为8,我们把它剪成的长度分别为2,3,3的三段,此时得到的最大的乘积是18。


思路

  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)
}

猜你喜欢

转载自blog.csdn.net/qq_40816360/article/details/95032134