#1547

Minimum Cost to Cut a Stick

Hard
ArrayDynamic ProgrammingSortingDynamic ProgrammingArray Manipulation
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n!)
O(n³)
Space
O(n)
O(n²)
💡

Intuition

Time O(n³)Space O(n²)

The optimal approach uses dynamic programming to minimize the cost of cuts by considering subproblems. It builds a DP table where each entry represents the minimum cost for a segment of the stick, allowing us to avoid redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Sort the cuts array and add 0 and n to the cuts for boundaries.
  2. 2Step 2: Create a DP table where dp[i][j] represents the minimum cost to cut the stick between cuts[i] and cuts[j].
  3. 3Step 3: Fill the DP table using the relation: dp[i][j] = min(dp[i][k] + dp[k][j] + (cuts[j] - cuts[i])) for all k between i and j.
solution.py11 lines
1def minCost(n, cuts):
2    cuts = [0] + sorted(cuts) + [n]
3    m = len(cuts)
4    dp = [[0] * m for _ in range(m)]
5    for length in range(2, m):
6        for i in range(m - length):
7            j = i + length
8            dp[i][j] = float('inf')
9            for k in range(i + 1, j):
10                dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + (cuts[j] - cuts[i]))
11    return dp[0][m - 1]

Complexity note: The time complexity is O(n³) due to the three nested loops: one for the length of the segment, one for the starting index, and one for the cut index. The space complexity is O(n²) for the DP table storing minimum costs.

  • 1The order of cuts significantly affects the total cost, so finding the optimal order is crucial.
  • 2Dynamic programming allows us to break down the problem into manageable subproblems, leading to an efficient solution.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.