Remix.run Logo
CamperBob2 5 days ago

I implemented the simple greedy algorithm and immediately fell into the trap of the question: the greedy algorithm only works for "well-behaved" denominations. If the coin values were [10, 9, 1], then making 37 cents would take 10 coins in the greedy algorithm but only 4 coins optimally (10+9+9+9).

That's a bad algorithm, then, not a greedy algorithm. Wouldn't a properly-implemented greedy algorithm use as many coins as possible of a given large denomination before dropping back to the next-lower denomination?

If a candidate's only options are to either use a constraint solver or to implement a naïver-than-usual greedy algorithm, well, sorry, but that's a no-hire.

Peritract 5 days ago | parent | next [-]

The algorithm they're using must be "Until you hit the limit, take the highest denomination coin that fits beneath the limit. If you can't hit the limit, fall back one step."

That fits your definition of "use as many coins as possible of a given large denomination before dropping back to the next-lower denomination" but will find 10-10-10-1-1-1-1-1-1-1 and stop before it even tries 10-9-anything.

smegma2 5 days ago | parent | prev | next [-]

There is no greedy solution to the problem. A greedy algorithm would start by taking 3 10-cent coins to make 37 which is wrong.

Jtsummers 5 days ago | parent | prev | next [-]

> Wouldn't a properly-implemented greedy algorithm use as many coins as possible of a given large denomination before dropping back to the next-lower denomination?

Yes, and it won't work on the problem described. The greedy algorithm only works on certain sets of coins (US coin denominations are one of those sets), and fails in at least some cases with other coin sets (as illustrated in the bit you quoted).

4 days ago | parent [-]
[deleted]
CamperBob2 4 days ago | parent | prev | next [-]

D'oh, that makes sense, I didn't consider the case where it would keep returning 10.

the_af 4 days ago | parent | prev [-]

By the way, ChatGPT was able to solve this problem and give the correct solution.

Jtsummers 4 days ago | parent | next [-]

It's in numerous algorithms textbooks and probably a lot of code repositories, so that's not surprising.

the_af 4 days ago | parent [-]

I didn't mean it was surprising. I meant literally what I said: I tried it, and it worked. Nothing more, nothing less.

the_af 4 days ago | parent | prev [-]

Interesting that an informative comment, without any implications or insinuations, got downvoted.

HN sucks sometimes. "Intellectual discourse" and "hacker curiosity" my ass.

CamperBob2 a day ago | parent [-]

I voted you back up. It's the least I could do. :)