r/learnjavascript • • Jan 26 '26

Help: Not able to write this algorithm

Hi all, I'm trying to figure out a way to make this work even with AI i can't make it work so i need your help.

I have this array of denominations = [5,10,20,50,100]; and this could be basically bills (eur, usd, ect).

I want to build a JavaScript function called generateBills that takes as params amount and days and returns an array of bills equal to the number of days and the total of these bills must be the amount itself at the end.

These bills must be bills from the denominations array and i want to find the best combination possible that has more small bills and continues progressively but at the same time avoid large bills (uses them only if necessary).

Example: generateBills(130, 4) might return [5,5,20,100] but a more balance way to avoid large bills should be [10,20,50,50].

Thanks!

1 Upvotes

24 comments sorted by

View all comments

Show parent comment

1

u/Beginning_Middle_722 Jan 27 '26

I will try to implement the knapsack solution but sure any help is appreciated. Thanks!

0

u/wbport1 Jan 27 '26

I was not aware of the knapsack problem when I wrote this. Here is the codepen link:

knapsack or cashed checks