Skip to content

Instantly share code, notes, and snippets.

@lisamariewatkins
Created September 22, 2017 18:32
Show Gist options
  • Save lisamariewatkins/7d13c88c60d372303d810dd4bebb1ed6 to your computer and use it in GitHub Desktop.
Save lisamariewatkins/7d13c88c60d372303d810dd4bebb1ed6 to your computer and use it in GitHub Desktop.
// Given an array of objects with a value and weight, figure out the combo to fit in your knapsack with the highest value
// There is an unlimited ammount of each object
public class Solution{
public class Item{
int value;
int weight;
public Item(int value, int weight){
this.value = value;
this.weight = weight;
}
}
public static int unboundedKnapsack(Item[] items, int capacity){
int[] capacities = new int[capacity + 1];
int maxSoFar = 0;
for(int currentCapacity = 0; currentCapacity < capacities; currentCapacity++){
int maxValue = 0;
for(Item item : items){
if(item.weight <= currentCapacity){
int weightDifference = currentCapacity - item.weight;
maxValue = Math.max(maxCapacity, (item.value + capacities[weightDifference]);
}
}
maxSoFar = Math.max(maxSoFar, maxValue);
}
return capacities[capacity];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment