Knapsack algorithm can be used to maximize combination of objects under restriction.
The sample knapsack problem looks like this.
You have a knapsack and 4 objects. The knapsack can carry 20kg, and each object's weight is 3kg, 8kg, 9kg, and 8kg. Each object is worth $10, $4, $9, and $11 respectively. Which objects should you put into your knapsack to make the most valuable out of 4 objects?
The explanation about how to approach this problem is found here. Scroll down to page 6 starting with heading Example #3: 0-1 Knapsack Problem
My code for this problem is this. I basically copied and pasted from the link. I renamed variables and put comments for myself.
Runtime Analysis
The code I presented above takes numObjects × maxWeights, because it is two nested loop. However, this problem can be solved by bruteforce. Altough bruteforce takes 2^n, the problem can be solved. Depending on the value of numObjects and maxWeights, bruteforce somestimes solve more efficient than knapsack algorithm.
For example, if numObjects = 5, maxWeights = 100000, bruteforce is better. If numObjects = 30, maxWeights = 1000, knapsack algorithm is better.