Assume that you havenyuan. There are many kinds of rice in the supermarket. Each kind of rice is bagged and must be purchased in the whole bag. Given theweight,priceandquantityof each type of rice, findthe maximum weightof rice that you can purchase.
public class Solution {
/**
* @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
*/
public int backPackVII(int n, int[] prices, int[] weight, int[] amounts) {
int m = prices.length;
// dp[i][j]: first ith prices, using j money, maximum weight
int[][] dp = new int[m + 1][n + 1];
dp[0][0] = 0;
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
dp[i][j] = dp[i - 1][j];
for (int k = 1; k <= amounts[i - 1]; k++) {
if (j >= k * prices[i - 1]) {
dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - k * prices[i - 1]] + k * weight[i - 1]);
}
}
}
}
return dp[m][n];
}
}
public int backPackVII(int n, int[] prices, int[] weight, int[] amounts) {
int all = prices.length;
int[] f = new int [n + 1];
for (int i = 1; i <= all; i++) {
for (int k = 1; k <= amounts[i - 1]; k++) {
for (int j = n; j >= prices[i - 1]; j--) {
f[j] = Math.max(f[j], f[j - prices[i - 1]] + weight[i - 1]);
}
}
}
return f[n];
}