Skip to content

Instantly share code, notes, and snippets.

@HDegano
Created June 18, 2015 01:18
Show Gist options
  • Save HDegano/63690ee1527c1d22512a to your computer and use it in GitHub Desktop.
Save HDegano/63690ee1527c1d22512a to your computer and use it in GitHub Desktop.
Knapsack 0/1 and Unbounded
public static partial class DynamicProgramming
{
public static int KnapSack_01(Tuple<int, int>[] valueWeightTuple, int maxWeight)
{
int[,] dp = new int[valueWeightTuple.Length + 1, maxWeight + 1];
for (int i = 0; i <= maxWeight; ++i) dp[0, i] = 0;
for (int i = 1; i <= valueWeightTuple.Length; i++)
{
int itemValue = valueWeightTuple[i - 1].Item1;
int itemWeight = valueWeightTuple[i - 1].Item2;
for (int j = 0; j <= maxWeight; j++)
{
if (itemWeight > j)
dp[i, j] = dp[i - 1, j];
else
{
dp[i, j] = Math.Max(dp[i - 1, j], dp[i - 1, j - itemWeight] + itemValue);
}
}
}
return dp[valueWeightTuple.Length, maxWeight];
}
public static int KnapSack_Unbounded(Tuple<int, int>[] valueWeightTuple, int maxWeight)
{
throw new NotImplementedException();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment