Skip to content

Instantly share code, notes, and snippets.

@shahzadaazam
Created January 22, 2019 07:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shahzadaazam/c7dd050e7d96a333340b4c55affd7d92 to your computer and use it in GitHub Desktop.
Save shahzadaazam/c7dd050e7d96a333340b4c55affd7d92 to your computer and use it in GitHub Desktop.
Bounded Knapsack Problem
public class Knapsack {
public static void main(String[] args) {
int val[] = new int[]{0, 60, 100, 120};
int wt[] = new int[]{0, 10, 20, 30};
int W = 50;
int n = val.length-1;
System.out.println(Knapsack.knapsack(wt, val, W, n));
}
public static int knapsack(int[] weights, int[] values, int capacity, int index) {
//base case
if (index <= 0 || capacity <= 0) return 0;
int result = 0;
if (weights[index] > capacity) {
result = knapsack(weights, values, capacity, index-1);
} else {
int temp1 = knapsack(weights, values, capacity, index-1);
int temp2 = values[index] + knapsack(weights, values, capacity-weights[index], index-1);
result = Math.max(temp1, temp2);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment