Rod cutting problem

Asked atMicrosoft
1Give yourself 5 minutes
2Answer out loud, not in your head
3Then compare with the answer below

The problem

Given a rod of length N inches and an array price[] where price[i] denotes the value of a piece of rod of length i inches (1-based indexing). Determine the maximum value obtainable by cutting up the rod and selling the pieces. Make any number of cuts, or none at all, and sell the resulting pieces.

Input: price = [1, 6, 8, 9, 10, 19, 7, 20], N = 8 Output: 25 Explanation: Cut the rod into lengths of 2 and 6 for a total price of 6 + 19= 25.

Input: price = [1, 5, 8, 9], N = 4 Output: 10 Explanation: Cut the rod into lengths of 2 and 2 for a total price of 5 + 5 = 10.

Input: price = [5, 5, 8, 9, 10, 17, 17, 20], N = 8

  • 1 ≤ N ≤ 1000
  • 1 ≤ price[i] ≤ 105

cpp

class Solution{
  public:
    int rodCutting(vector<int> price, int n) {
     
    }
};

java

class Solution{
    public int RodCutting(int price[], int n) {
    }
}

python

class Solution:
    def RodCutting(self, price, n):

javascript

class Solution {
    RodCutting(price, n) {
       
    }
}

csharp

class Solution
{
    public int RodCutting(int[] price, int n)
    {
    }
}

go

func RodCutting(price []int, n int) int {
	
}
Stuck? Show a way to structure it+
  1. 01Let dp[len] be the best revenue for a rod of length len.
  2. 02For every allowed piece length, consider taking it plus dp of the remainder.
  3. 03Allow reusing the same piece length.
  4. 04Return dp[N].

Reference answer

Then expect these follow-ups

  • How would you return the actual cut lengths?

    Tests: DP reconstruction

  • Why is this equivalent to unbounded knapsack?

    Tests: problem reduction

Hiring now

Software engineer roles are open right now

landed applies to roles like these for you, on each company’s own site, with answers written for the role.

Get 5x interviews10 free auto-applies. No card.
  • Senior Software Engineer -.NET

    Tyler Technologies · Annapolis, Maryland

  • Software Development Engineer II

    SaaS Labs · Bengaluru, Karnataka, India

  • Advanced Software Engineer - Product Architect (Legal, Safety, and Risk)

    Metropolitan Transportation Authority · New York, NY

Or practice this question first

Next question