public int Weight { get; set; }
public int Value { get; set; }
public static void Main()
int[] value = { 60, 100, 120 };
int[] weight = { 10, 20, 30 };
int result = KnapSack(capacity, weight, value, itemsCount);
Console.WriteLine(result);
new Item {Value = 60, Weight = 10},
new Item {Value = 100, Weight = 20},
new Item {Value = 120, Weight = 30},
Console.WriteLine(KnapSack(items, 50));
Console.WriteLine(KnapSackRecursive(items, 50));
public static int KnapSack(Item[] items, int capacity)
int[,] matrix = new int[items.Length + 1, capacity + 1];
for (int itemIndex = 0; itemIndex <= items.Length; itemIndex++)
var currentItem = itemIndex == 0 ? null : items[itemIndex - 1];
for (int currentCapacity = 0; currentCapacity <= capacity; currentCapacity++)
if (currentItem == null || currentCapacity == 0)
matrix[itemIndex, currentCapacity] = 0;
else if (currentItem.Weight <= currentCapacity)
matrix[itemIndex, currentCapacity] = Math.Max(
+ matrix[itemIndex - 1, currentCapacity - currentItem.Weight],
matrix[itemIndex - 1, currentCapacity]);
matrix[itemIndex, currentCapacity] =
matrix[itemIndex - 1, currentCapacity];
return matrix[items.Length, capacity];
public static int KnapSackRecursive(Item[] items, int capacity)
if (items.Length == 0 || capacity == 0) return 0;
return items[0].Weight < capacity ? items[0].Value : 0;
for (int i = 0; i < items.Length; i++)
var otherItems = items.Take(i).Concat(items.Skip(i + 1)).ToArray();
int without = KnapSackRecursive(otherItems, capacity);
if (items[i].Weight <= capacity)
with = KnapSackRecursive(otherItems, capacity - items[i].Weight)
int currentBest = Math.Max(without, with);
public static int KnapSack(int capacity, int[] weight, int[] value, int itemsCount)
int[,] K = new int[itemsCount + 1, capacity + 1];
for (int i = 0; i <= itemsCount; ++i)
for (int w = 0; w <= capacity; ++w)
else if (weight[i - 1] <= w)
K[i, w] = Math.Max(value[i - 1] + K[i - 1, w - weight[i - 1]], K[i - 1, w]);
return K[itemsCount, capacity];