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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started