|
| 1 | +/** |
| 2 | + * 1547. Minimum Cost to Cut a Stick |
| 3 | + * https://leetcode.com/problems/minimum-cost-to-cut-a-stick/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * Given a wooden stick of length n units. The stick is labelled from 0 to n. For example, a |
| 7 | + * stick of length 6 is labelled as follows. |
| 8 | + * |
| 9 | + * Given an integer array cuts where cuts[i] denotes a position you should perform a cut at. |
| 10 | + * |
| 11 | + * You should perform the cuts in order, you can change the order of the cuts as you wish. |
| 12 | + * |
| 13 | + * The cost of one cut is the length of the stick to be cut, the total cost is the sum of costs |
| 14 | + * of all cuts. When you cut a stick, it will be split into two smaller sticks (i.e. the sum of |
| 15 | + * their lengths is the length of the stick before the cut). Please refer to the first example |
| 16 | + * for a better explanation. |
| 17 | + * |
| 18 | + * Return the minimum total cost of the cuts. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number} n |
| 23 | + * @param {number[]} cuts |
| 24 | + * @return {number} |
| 25 | + */ |
| 26 | +var minCost = function(n, cuts) { |
| 27 | + cuts.push(0, n); |
| 28 | + cuts.sort((a, b) => a - b); |
| 29 | + |
| 30 | + const memo = new Map(); |
| 31 | + |
| 32 | + return computeMinCost(0, cuts.length - 1); |
| 33 | + |
| 34 | + function computeMinCost(left, right) { |
| 35 | + if (right - left <= 1) return 0; |
| 36 | + |
| 37 | + const key = `${left},${right}`; |
| 38 | + if (memo.has(key)) return memo.get(key); |
| 39 | + |
| 40 | + let minCost = Infinity; |
| 41 | + for (let i = left + 1; i < right; i++) { |
| 42 | + const cost = (cuts[right] - cuts[left]) + computeMinCost(left, i) + computeMinCost(i, right); |
| 43 | + minCost = Math.min(minCost, cost); |
| 44 | + } |
| 45 | + |
| 46 | + memo.set(key, minCost); |
| 47 | + return minCost; |
| 48 | + } |
| 49 | +}; |
0 commit comments