The Knapsack Problem is a classic optimization problem where you aim to maximize the total value of items you can carry in a knapsack with a fixed weight capacity. Here’s an outline of the optimal solution using dynamic programming.
Given:
Objective: Maximize the total value of the items in the knapsack without exceeding the weight capacity.
dp
where dp[i][w]
represents the maximum value that can be achieved with the first i
items and a maximum weight capacity of w
.dp[0][w] = 0
and dp[i][0] = 0
.dp[n][W]
, where n
is the total number of items and W
is the maximum weight capacity.#include <iostream>
#include <vector>
using namespace std;
int knapsack(int W, vector<int>& weights, vector<int>& values, int n) {
vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));
for (int i = 1; i <= n; i++) {
for (int w = 1; w <= W; w++) {
if (weights[i - 1] <= w) {
dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weights[i - 1]] + values[i - 1]);
} else {
dp[i][w] = dp[i - 1][w];
}
}
}
return dp[n][W];
}
int main() {
int W = 50;
vector<int> weights = {10, 20, 30};
vector<int> values = {60, 100, 120};
int n = values.size();
int maxValue = knapsack(W, weights, values, n);
cout << "Maximum value in the Knapsack = " << maxValue << endl;
return 0;
}
Maximum value in the Knapsack = 220
knapsack
function builds a DP table where each entry dp[i][w]
contains the maximum value obtainable with the first i
items and weight limit w
.