Algorithm to find elements best fitting in a particular amount

后端 未结 5 890
遇见更好的自我
遇见更好的自我 2021-01-17 03:32

I\'m looking for an algorithm to solve the follwoing problem (I will explain it with an example):

Let say I have 10.000 $ available amount and following costs I can

5条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-17 03:56

    I can't improve your solution for general data, however there are few improvements which can speed it up.

    If total amount N is quite low there is simple dynamic solution:

    setOfValues
    put totalAmount to setOfValues
    foreach cost do
        foreach amount in setOfValues do
            if (amount - cost) > 0 and not exists (amount - cost) in setOfValues
                put (amount - cost) to setOfValues
    get lowest setOfValues
    

    You can simple upgrade it to additional requirements (like up to x costs).

提交回复
热议问题