Created
September 22, 2017 18:32
-
-
Save lisamariewatkins/7d13c88c60d372303d810dd4bebb1ed6 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| // 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