Solution Implemented in C#

suggest change
public 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];
    }
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents