r/shittyprogramming • • Mar 23 '19

Expert Mode Greedy Algorithm

So I've got some homework and I'm stuck on the mathematical part rather than coding part.

Basically its a truck problem or a bin problem with varying capacity.

You have an infinite amount of n types of boats. (the user inputs n), and each holds a different amount of cargo (which is also user defined)(but the smallest amount is always 1 as a given). And the purpose is to find the minimum number of ships needed to move that much cargo.

say you got 4 types of boats and they respectively hold

1 5 6 9

Say you get a customer who wants to move 40 units.

now using the greedy method i get

9+9+9+9+1+1+1+1 for a total of 8 boats needed.

However (as the teacher provided us with some inputs and outputs),

9+9+9+6+6+1 = 6 boats.

What kind of algorithm must I use to work this out, because the greedy algo is being greedy and not working for me.

22 Upvotes

8 comments sorted by

View all comments

Show parent comment

5

u/Gbroxey Mar 23 '19

no problem! make sure you don't do simple recursion without memoization though, that'll destroy your runtime (exponential in the number of units required). If you use an array to keep track of past values it'll be linear.