- Backpack VII
中文English
Assume that you have n yuan. There are many kinds of rice in the supermarket. Each kind of rice is bagged and must be purchased in the whole bag. Given the weight, price and quantity of each type of rice, find the maximum weight of rice that you can purchase.
Example
Example 1:
Input: n = 8, prices = [3,2], weights = [300,160], amounts = [1,6]
Output: 640
Explanation: Buy the second rice(price = 2) use all 8 money.
Example 2:
Input: n = 8, prices = [2,4], weight = [100,100], amounts = [4,2 ]
Output: 400
Explanation: Buy the first rice(price = 2) use all 8 money.
解法1:
class Solution {
public:
/**
* @param n: the money of you
* @param prices: the price of rice[i]
* @param weight: the weight of rice[i]
* @param amounts: the amount of rice[i]
* @return: the maximum weight
*/
int backPackVII(int n, vector<int> &prices, vector<int> &weight, vector<int> &amounts) {
int itemCount = prices.size(); //count of items
vector<vector<int>> dp(itemCount + 1, vector<int>(n + 1, 0)); //dp[i][j] means the maximum weight of first i tems with total price <= j
for (int i = 1; i <= itemCount; ++i) {
for (int k = 1; k <=n; ++k) {
dp[i][k] = dp[i - 1][k];
}
for (int j = 0; j <= amounts[i - 1]; ++j) {
for (int k = 1; k <= n; ++k) { //k-> 1 .. n
if (k >= j * prices[i - 1]) {
dp[i][k] = max(dp[i][k], dp[i - 1][k - j * prices[i - 1]] + j * weight[i - 1]);
}
}
}
}
return dp[itemCount][n];
}
};
解法2:
代码如下:
class Solution {
public:
/**
* @param n: the money of you
* @param prices: the price of rice[i]
* @param weight: the weight of rice[i]
* @param amounts: the amount of rice[i]
* @return: the maximum weight
*/
int backPackVII(int n, vector<int> &prices, vector<int> &weight, vector<int> &amounts) {
int itemCount = prices.size();
vector<int> dp(n + 1, 0);
for (int i = 1; i <= itemCount; ++i) {
for (int j = 1; j <= amounts[i - 1]; ++j) {
for (int k = n; k >= prices[i - 1]; --k) {
dp[k] = max(dp[k], dp[k - prices[i - 1]] + weight[i - 1]);
}
}
}
return dp[n];
}
};