Working soluton to knapsack problem (dynamic programming)