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 locations where the cuts are to be made for maximum profit.
I need help how can we approach this problem ?
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 locations where the cuts are to be made for maximum profit.
I need help how can we approach this problem ?
A simple recursion can solve this problem:
#include <algorithm>
#include <climits>
int maxPrice(int prices[], int n) {
if (n <= 0) return 0;
int ans = INT_MIN;
for (int i = 0; i < n; i++)
ans = std::max(ans, prices[i] + maxPrice(prices, n - i - 1));
return ans;
}
int main(){
//size: 1 2 3 4 5 6 7 8
int prices[] = {1, 3, 4, 8, 9, 11, 11, 16};
std::cout<<maxPrice(prices, 8)<<std::endl;
return 0;
}
On the other hand, this solution is slow. The best option would be taking the knapsack problem approach: consider you have a knapsack of size n and each piece of size (or weight in this case) i costs p[i], then just fill the matrix as the common knapsack would do. The idea would be to preprocess the best price for itens at each size until n.