Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Conceptual Database Design An Entity Relationship Approach

Authors: Carol Batini, Stefano Ceri, Shamkant B. Navathe

1st Edition

0805302441, 978-0805302448

Students also viewed these Databases questions