Question 1 : Rob-Cutting
Given a rod of length n inches and an array of prices that contains prices of all pieces of size smaller than n. Determine the maximum value obtainable by cutting up the rod and selling the pieces.
vector<int> price = {1,5,8,9,10,17,17,20,24,30};
Input: 3
Output: 8
Input: 4
Output: 10
Solution 1: Dynamic Programming (recursive version - Top to Bottom)
int help(const vector<int> price,int n,vector<int> res){
if(res[n] >= 0){
return res[n];
}
if(n == 0){
return 0;
}
int cut = INT_MIN;
for(int i = 1; i <=n; i++){
cut = max(cut,price[i - 1] + help(price,(n - i),res));
}
res[n] = cut;
return cut;
}
int robcut(const vector<int> price,int n){
vector<int> res;
for(int i = 0; i <= n; i++){
res.push_back(-1);
}
return help(price,n, res);
}
Explanation: Every can seperate the problem by computing every possible cutting position. In the 'help' function, the 'for' loop is to cut from the first position to n position. Using 'res' to prevent repetitive computation.
Note: Pay attention to the index of 'price' and 'help' in the loop.
Solution 2: Dynamic Programming (normal version - Bottom to Top)
int robcut2(const vector<int> price, int n){
vector<int> res;
int i;
for(i = 0; i <= n; i++){
res.push_back(INT_MIN);
}
res[0] = 0;
for(i = 1; i <= n; i++){
for(int j = 1; j <= i; j++){
res[i] = max(res[i],price[j - 1] + res[i - j]);
}
}
return res[n];
}
Explanation: Compute the smaller question first and store the result in 'res'. When big problem use it, just take it from the 'res'.
Similar Question : Leetcode 241. Different Ways to Add Parentheses (Solution is in "Divide and Conquer").