Inventory planning problem solved through dynamic programming
CLRS give plenty of implementations in their chapter on dynamic programming, e.g. in the section on Rod cutting


recursive top-down (p363),
memoized (p365f) and
bottom-up (p366).


I suggest you try to adapt one of these.