Created
January 22, 2019 07:49
-
-
Save shahzadaazam/c7dd050e7d96a333340b4c55affd7d92 to your computer and use it in GitHub Desktop.
Bounded Knapsack Problem
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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