imperative knapsack with caching