Program to find minimum cost to cut a stick in Python

Given a wooden stick of length n and an array of cut positions, we need to find the minimum cost to make all cuts. The cost of each cut equals the length of the current stick segment being cut. This is a classic dynamic programming problem that can be solved optimally by choosing the right order of cuts.

Problem Understanding

Consider a stick of length 7 with cuts at positions [5,1,4,3]. The total cost depends on the order we make the cuts ?

  • Each cut costs the length of the current stick segment

  • We can reorder cuts to minimize total cost

  • The goal is to find the optimal cutting sequence

Algorithm Approach

We use dynamic programming with the following strategy ?

  • Add boundary points (0 and n) to the cuts array

  • Sort all cut positions

  • Use interval DP to find minimum cost for each segment

  • For each segment, try all possible intermediate cuts

Implementation

def min_cost_cutting(n, cuts):
    # Add boundaries and sort
    cuts = [0] + sorted(cuts) + [n]
    m = len(cuts)
    
    # Initialize DP table
    cost = [[0] * m for _ in range(m)]
    
    # Fill DP table for increasing segment lengths
    for length in range(2, m):
        for i in range(m):
            j = i + length
            if j >= m:
                continue
            
            # Try all possible cuts between i and j
            segment_cost = cuts[j] - cuts[i]
            min_split_cost = float('inf')
            
            for k in range(i + 1, j):
                split_cost = cost[i][k] + cost[k][j]
                min_split_cost = min(min_split_cost, split_cost)
            
            cost[i][j] = segment_cost + min_split_cost
    
    return cost[0][m - 1]

# Test the solution
n = 7
cuts = [5, 1, 4, 3]
result = min_cost_cutting(n, cuts)
print(f"Minimum cost to cut stick of length {n}: {result}")
Minimum cost to cut stick of length 7: 16

How It Works

Let's trace through the example step by step ?

def min_cost_cutting_detailed(n, cuts):
    print(f"Original cuts: {cuts}")
    
    # Add boundaries and sort
    cuts = [0] + sorted(cuts) + [n]
    print(f"After adding boundaries and sorting: {cuts}")
    
    m = len(cuts)
    cost = [[0] * m for _ in range(m)]
    
    # Fill DP table
    for length in range(2, m):
        print(f"\nProcessing segments of length {length}:")
        for i in range(m):
            j = i + length
            if j >= m:
                continue
            
            segment_length = cuts[j] - cuts[i]
            min_split_cost = float('inf')
            best_cut = -1
            
            for k in range(i + 1, j):
                split_cost = cost[i][k] + cost[k][j]
                if split_cost < min_split_cost:
                    min_split_cost = split_cost
                    best_cut = k
            
            cost[i][j] = segment_length + min_split_cost
            print(f"  Segment [{cuts[i]}, {cuts[j]}]: cost = {cost[i][j]}")
    
    return cost[0][m - 1]

# Test with detailed output
n = 7
cuts = [5, 1, 4, 3]
result = min_cost_cutting_detailed(n, cuts)
print(f"\nFinal minimum cost: {result}")
Original cuts: [5, 1, 4, 3]
After adding boundaries and sorting: [0, 1, 3, 4, 5, 7]

Processing segments of length 2:
  Segment [0, 3]: cost = 3
  Segment [1, 4]: cost = 3
  Segment [3, 5]: cost = 2
  Segment [4, 7]: cost = 3

Processing segments of length 3:
  Segment [0, 4]: cost = 6
  Segment [1, 5]: cost = 6
  Segment [3, 7]: cost = 6

Processing segments of length 4:
  Segment [0, 5]: cost = 9
  Segment [1, 7]: cost = 9

Processing segments of length 5:
  Segment [0, 7]: cost = 16

Final minimum cost: 16

Time and Space Complexity

Aspect Complexity Explanation
Time O(m³) Three nested loops over m cuts
Space O(m²) 2D DP table of size m × m

Key Points

  • Adding boundaries (0 and n) simplifies the DP formulation

  • Sorting cuts ensures we process segments in correct order

  • Each subproblem represents the minimum cost to cut a segment

  • The cost of cutting a segment always includes its full length

Conclusion

This dynamic programming solution finds the minimum cost to cut a stick by considering all possible cutting orders. The key insight is that the cost of any cut equals the length of the current segment, making optimal substructure possible.

Updated on: 2026-03-26T14:09:48+05:30

858 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements