Solves the knapsack problem using dynamic programming.