Rod cutting problem

Pattern: Subsequences and knapsack

medium

A rod of length n can be cut into pieces sold at price[length - 1]. Each piece length can be used many times, so it is unbounded knapsack where the weight of a piece is its length.

The problem

Given price[i], the price of a piece of length i + 1, and a rod of length n = price.length, return the most money from cutting it into pieces and selling them.

Think first

  • What was the last piece cut?
  • What is left after it?
  • How is this a knapsack?

Hints

    Brute force, and why it fails

    Try every way to cut: 2ⁿ⁻¹.

    The key insight

    The best price for each length depends only on shorter lengths.

    Dry run

    prices [1, 5, 8, 9, 10, 17, 17, 20], length 8.

    Step 1 of 2

    The plan

    best[0] = 0
    for m in 1..n: best[m] = max over L of price[L - 1] + best[m - L]
    

    Complexity

    Time
    O(n²)
    Space
    O(n)

    n choices per length.

    Edge cases

    • Length 1.
    • No cut is best.
    • All prices equal.
    I've built my logic, show the code

    Java

    class Solution {
        public int rodCutting(int[] price) {        // price[i] is the price of a piece of length i + 1
            int n = price.length;
            int[] best = new int[n + 1];            // best[len]: the most for a rod of length len
            for (int len = 1; len <= n; len++)
                for (int cut = 1; cut <= len; cut++) best[len] = Math.max(best[len], price[cut - 1] + best[len - cut]);   // first piece
            return best[n];
        }
    }

    C++

    class Solution {
    public:
        int rodCutting(vector<int>& price) {        // price[i] is the price of a piece of length i + 1
            int n = static_cast<int>(price.size());
            vector<int> best(n + 1, 0);             // best[len]: the most for a rod of length len
            for (int len = 1; len <= n; len++)
                for (int cut = 1; cut <= len; cut++) best[len] = max(best[len], price[cut - 1] + best[len - cut]);   // first piece
            return best[n];
        }
    };

    Python

    class Solution:
        def rodCutting(self, price: list[int]) -> int:   # price[i] is the price of a piece of length i + 1
            n = len(price)
            best = [0] * (n + 1)                    # best[len]: the most for a rod of length len
            for length in range(1, n + 1):
                best[length] = max(price[cut - 1] + best[length - cut] for cut in range(1, length + 1))   # first piece
            return best[n]

    Common mistakes

    • Off-by-one between length and index.
    • Forgetting the uncut rod.

    Similar problems