optimized knapsack for well formed output