C Online Compiler
Example: Solve 0/1 Knapsack Problem in C
C
C++
C#
Java
Python
PHP
main.c
STDIN
Run
// Solve 0/1 Knapsack Problem in C #include <stdio.h> int maxSize(int a, int b); int solveKnapSack(int W, int wt[], int val[], int n); // It's the driver function int main() { int val[] = { 60, 100, 120 }, wt[] = { 10, 20, 30 }, W = 50; int n = sizeof(val) / sizeof(val[0]); // This will print the solution of 0-1 Knapsack problem printf("The solution of 0-1 Knapsack problem is: %d\n", solveKnapSack(W, wt, val, n)); return 0; } // This will return max size of the value int maxSize(int a, int b) { return (a > b) ? a : b; } // This function will solve the 0 1 knapsack problem int solveKnapSack(int W, int wt[], int val[], int n) { if (n == 0 || W == 0) return 0; // 1. If the weight of the nth item is more than // 2. Knapsack capacity W, then this item cannot be included in the optimal solution if (wt[n - 1] > W) return solveKnapSack(W, wt, val, n - 1); // It returns the maximum of two cases: // 1. nth item included // 2. not included else return maxSize(val[n - 1] + solveKnapSack(W - wt[n - 1], wt, val, n - 1), solveKnapSack(W, wt, val, n - 1)); }
Output
Clear
ADVERTISEMENTS