Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
0-1 Knapsack Problem in C?
The 0-1 Knapsack Problem is a classic dynamic programming problem where we have a knapsack with a fixed capacity and a set of items, each with a weight and value. The goal is to maximize the total value of items in the knapsack without exceeding its weight capacity. In the 0-1 variant, each item can either be included (1) or excluded (0) − no fractional items are allowed.
Syntax
int knapsack(int capacity, int weights[], int values[], int n);
Sample Problem
Items: 3
Values: {20, 25, 40}
Weights: {25, 20, 30}
Knapsack Capacity: 50
Weight Distribution Analysis
Possible combinations:
Item {1,2}: weight = 25+20 = 45, value = 20+25 = 45
Item {1,3}: weight = 25+30 = 55 (exceeds capacity)
Item {2,3}: weight = 20+30 = 50, value = 25+40 = 65
Maximum value: 65 (items 2 and 3)
Dynamic Programming Approach
The solution uses a 2D table where dp[i][w] represents the maximum value achievable using the first i items with weight limit w.
#include <stdio.h>
int max(int a, int b) {
return (a > b) ? a : b;
}
int knapsack(int W, int wt[], int val[], int n) {
int i, w;
int dp[n + 1][W + 1];
// Build table dp[][] in bottom-up manner
for (i = 0; i <= n; i++) {
for (w = 0; w <= W; w++) {
if (i == 0 || w == 0) {
dp[i][w] = 0;
}
else if (wt[i - 1] <= w) {
dp[i][w] = max(val[i - 1] + dp[i - 1][w - wt[i - 1]],
dp[i - 1][w]);
}
else {
dp[i][w] = dp[i - 1][w];
}
}
}
return dp[n][W];
}
int main() {
int val[] = {20, 25, 40};
int wt[] = {25, 20, 30};
int W = 50;
int n = sizeof(val) / sizeof(val[0]);
printf("Items: %d<br>", n);
printf("Knapsack Capacity: %d<br>", W);
printf("Maximum value: %d<br>", knapsack(W, wt, val, n));
return 0;
}
Items: 3 Knapsack Capacity: 50 Maximum value: 65
How It Works
- Base Case: If no items or no capacity, value is 0
- Choice: For each item, decide to include or exclude it
- Include: Add item's value + optimal value with remaining capacity
- Exclude: Take optimal value without current item
- Optimal: Choose maximum of include/exclude options
Time Complexity
- Time Complexity: O(n × W) where n is number of items and W is capacity
- Space Complexity: O(n × W) for the DP table
Conclusion
The 0-1 Knapsack problem is efficiently solved using dynamic programming with O(n × W) time complexity. The algorithm builds an optimal solution by considering all possible combinations while avoiding redundant calculations through memoization.
