Solution Implemented in C#
suggest changepublic static class KnapsackProblem
{
public static int Solve(int capacity, int[] weights, int[] values)
{
if (weights.Length != values.Length || capacity < 0)
throw new System.ArgumentException("Invalid knapsack input");
var best = new int[capacity + 1];
for (int item = 0; item < weights.Length; item++)
{
if (weights[item] <= 0)
throw new System.ArgumentException("Weights must be positive");
for (int limit = capacity; limit >= weights[item]; limit--)
best[limit] = System.Math.Max(
best[limit], best[limit - weights[item]] + values[item]);
}
return best[capacity];
}
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents