Java Online Compiler
Example: Solve 0/1 Knapsack Problem in Java
C
C++
C#
Java
Python
PHP
Main.java
STDIN
Run
// Solve 0/1 Knapsack Problem in Java import java.util.Scanner; public class Main { // It's the driver function public static void main(String[] args) { Scanner in = new Scanner(System.in); Main main = new Main(); int[] val = { 60, 100, 120 }; int[] wt = { 10, 20, 30 }; int W = 50; int n = val.length; // This will print the solution of 0-1 Knapsack problem System.out.println("The solution of 0-1 Knapsack problem is: " + main.solveKnapSack(W, wt, val, n)); } // 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 this.solveKnapSack(W, wt, val, n - 1); // It returns the maximum of two cases: // 1. nth item included // 2. not included else return this.maxSize(val[n - 1] + this.solveKnapSack(W - wt[n - 1], wt, val, n - 1), this.solveKnapSack(W, wt, val, n - 1)); } // This will return max size of the value int maxSize(int a, int b) { return (a > b) ? a : b; } }
Output
Clear
ADVERTISEMENTS