KatInterview

Best Revenue from Selling Rod Segments

Dynamic ProgrammingAuto-graded · 22 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingoptimizationunbounded-knapsack

Last updated

Tests dynamic programming by finding the optimal way to partition a rod into segments to maximize total selling price.

You have a rod measuring rod_length meters. You also have a list segment_prices where segment_prices[i] represents how much you can sell a segment of exactly i + 1 meters for.

You need to decide how to partition the rod into segments (each an integer number of meters) to maximize your total revenue. You may cut the rod into any number of pieces, or sell it uncut.

Write a function that returns the maximum revenue achievable.

Constraints

  • 1 <= rod_length <= 1000
  • len(segment_prices) == rod_length
  • 1 <= segment_prices[i] <= 10^5

Examples

Example 1

Input: best_rod_revenue(4, [1, 5, 8, 9])

Output: 10

Example 2

Input: best_rod_revenue(8, [3, 5, 8, 9, 10, 17, 17, 20])

Output: 24

Hints

Hint 1

Consider what happens when you decide the length of the first segment you sell—what problem remains?

Hint 2

Build a table where entry i stores the best revenue for a rod of length i, using previously computed smaller lengths.

Hint 3

For each length, try all possible first-segment choices and take the maximum revenue.