[Coding Made Simple] Cutting Rod for max profit

Given a rod of length and prices at which different length of this rod can sell, how do you cut this rod to maximize profit.

 

Solution. Dynamic Programming

State: T[i][j]: the max profit when the rod's length is j and the first i cutting methods are available. 

Function: T[i][j] = max{T[i - 1][j],  entries[i - 1].profit + T[i][j - entries[i - 1].len]},   if j >= entries[i - 1].len;

     T[i][j] = T[i - 1][j], if j < entries[i - 1].len;

For a given cutting method of certain length and profit, we can only use this method when the current rod's length is at least as long as the cut length.

1. If the current rod's length is shorter than the cut length, then the max profit we can have is simply the same rod's length without using this cut length at all. 

2. Otherwise, the max profit is the max of either not using the current cut length or using it. 

 

 1 import java.util.ArrayList;
 2 
 3 class LenAndProfit {
 4     int len;
 5     int profit;
 6     LenAndProfit(int l, int p) {
 7         this.len = l;
 8         this.profit = p;
 9     }
10 }
11 public class CuttingRod {
12     private ArrayList<Integer> cuts;
13     public int getMaxProfit(int totalLen, LenAndProfit[] entries) {
14         int[][] T = new int[entries.length + 1][totalLen + 1];
15         for(int i = 0; i <= entries.length; i++) {
16             T[i][0] = 0;
17         }
18         for(int j = 0; j <= totalLen; j++) {
19             T[0][j] = 0;
20         }
21         for(int i = 1; i < T.length; i++) {
22             for(int j = 1; j <= totalLen; j++) {
23                 if(j >= entries[i - 1].len) {
24                     T[i][j] = Math.max(T[i - 1][j], entries[i - 1].profit + T[i][j - entries[i - 1].len]);
25                 }
26                 else {
27                     T[i][j] = T[i - 1][j];
28                 }
29             }
30         }
31         cuts = getMaxProfitCut(T, entries);
32         return T[entries.length][totalLen];
33     }
34     private ArrayList<Integer> getMaxProfitCut(int[][] T, LenAndProfit[] entries) {
35         ArrayList<Integer> cuts = new ArrayList<Integer>();
36         int i = T.length - 1, j = T[0].length - 1;
37         while(T[i][j] != 0) {
38             if(T[i - 1][j] == T[i][j]) {
39                 i--;
40             }
41             else {
42                 cuts.add(entries[i - 1].len);
43                 j -= entries[i - 1].len;
44             }
45         }
46         return cuts;
47     }
48 }

 

Related Problems

BackPack

posted @ 2017-08-18 02:10  Review->Improve  阅读(218)  评论(0编辑  收藏  举报