r/PHPhelp • u/ser_89 • Oct 25 '22
Greedy Algorithm with added functionality.
I have a specific function that I require assistance with. I am busy with a project where licenses need to be allocated based on a specific quantity as per user input. The licenses are bundled as an example 1 user, 5 users, 10 users 20 users and 50 users. If the input is 20 it's easy to determine that the license that needs to be allocated is one for 20 users. If the input is 27 I can use a greedy algorithm to determine the best way to allocate would be 1 x 20 users, 1 x 5 users and 2 x 1 user.
My problem now though is that in most cases there is a threshold where it is actually more cost effective to rather allocate a license that caters for more users compared to the input specified. For example 19 users it is more cost effective to provide a license for 20 compared to 1 x 10 users, 1 x 5 users and 4 x 1 user.
What would be the best approach to approach the above and avoid unnecessary recalculation and comparison. The obvious approach is to run the greedy algorithm and get a total cost and compare the cost of another license where total users > users as per input.
The issue I see is already making me scratch my head. Is for example 28 users. I already know the most cost effective approach is 1 x 20 users and 1 x 10 users. The next license up is 50 users. So it will be too expensive. However the greedy algorithm gives me 1 x 20 user, 1 x 5 user and lastly 3 x 1 user.
Any assistance will be greatly appreciated.
1
u/richardathome Oct 25 '22
What's the maximum number of licences someone would buy? 100? 200?
Pre-calculate (by hand in necessary) and store the result in some common memory and just look it up.