To prove safety OFFER ---- 14, cut the rope (js achieve)

topic

You give a string of length n, m please cut the rope section (m, n) is a positive integer, (n> 1 & m> 1)

Length of each string is k [0], k [1], k [2], ..., k [m]. Will k [0] k [1] maximum value k [2] ... k [m] is.

8, for example, a length of rope, we cut it into three lengths of 2,3,3 maximum product obtained at this time was 18.


Thinking

  1. Dynamic Programming. Start to start with the lowest and the resulting product can be cut after each performance the number of stored maximum value. When the calculated value of the time of the subsequent use of the maximum value already stored good, calculating all possible outcomes and retain maximum. Time complexity of O (n * n) space complexity of O (n)

  2. how are you


// 动态规划
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)
}

Guess you like

Origin blog.csdn.net/qq_40816360/article/details/95032134