Online store: Optimal discount calculation method

Hey everyone, I’m working on an online store project and I’m stuck with a tricky problem. I need to figure out the best way to calculate discounts for customer orders. Here’s what I’m dealing with:

  • Lots of products, each with a unique ID and price
  • Multiple discount types that can apply to different products
  • Each item can only get one discount

I’ve tried a simple approach:

  1. Clear all discounts
  2. Get all product IDs in the cart
  3. Find all available discounts for these products
  4. Apply discounts one by one to eligible items

But this doesn’t work well because it doesn’t try different combinations of discounts to find the best deal for the customer.

Has anyone tackled a similar problem before? I’m looking for ideas on how to efficiently calculate the optimal discount combination, especially when dealing with 30-40 items in a cart and multiple possible discounts per item.

Any tips or algorithms that could help would be awesome. Thanks!

I’ve dealt with a similar challenge in my e-commerce projects. Instead of applying discounts sequentially, consider using a dynamic programming approach. Create a matrix where rows represent items and columns represent discount combinations, then fill the matrix with the best discount for each item-combination pair and backtrack to find the optimal overall discount. For larger carts, a greedy algorithm can serve as a first pass, followed by local search or simulated annealing to refine the result. Additionally, caching frequently used discount combinations for common product groupings can significantly improve performance.

hey leo, try a greedy algo.

it may not always yield best discount but is fast. start with top discount and skip already discounted items. add a time limit for large carts. just my 2 cents!

Hey Leo_Speedster! That’s a super interesting problem you’ve got there. Have you thought about approaching it from a different angle? Maybe instead of trying to find the absolute best combination, you could use a ‘good enough’ approach?

Like, what if you sorted the discounts by their potential value and applied them in that order? It might not always give the perfect result, but it could be way faster and still pretty good for the customers.

Or here’s a wild idea - what if you turned it into a game for the customers? Let them mix and match discounts themselves, within certain limits. Could be fun for them and take some load off your system.

Just throwing ideas out there! What do you think? Have you considered any approaches like these?