Question: public class BruteForceKnapsack { public static int knapsack(int[] weights, int[] values, int maxWeight, int numItems) { if (numItems == 0 || maxWeight == 0) return

public class BruteForceKnapsack {

public static int knapsack(int[] weights, int[] values, int maxWeight, int numItems) { if (numItems == 0 || maxWeight == 0) return 0;

if (weights[numItems - 1] > maxWeight) return knapsack(weights, values, maxWeight, numItems - 1);

return Math.max( knapsack(weights, values, maxWeight, numItems - 1), values[numItems - 1] + knapsack(weights, values, maxWeight - weights[numItems - 1], numItems - 1) ); }

public static void main(String[] args) { int[] weights = {2, 3, 4, 5}; int[] values = {3, 4, 5, 6}; int maxWeight = 5; int numItems = weights.length;

int maxValue = knapsack(weights, values, maxWeight, numItems); System.out.println("Maximum value that can be obtained: " + maxValue); } }

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!