There are a number of closely-related questions here whose answers may help: Chicken Mcnugget Theorem (Frobenous Coin) Problem,
Least wasteful use of stamps to achieve a given postage, and
Using only postage stamps of value 64 and 55, how can I work out the way to get closest to a high parcel value?
Using the example of candy bars that come in two sizes by weight,
$a$ grams or $b$ grams,
clearly the only amounts that can be purchased exactly are multiples of
$\gcd(a,b).$
If the amount we need is not a multiple of $\gcd(a,b),$
we'll have to buy enough "wasted" candy to bring the total weight up to
a multiple of $\gcd(a,b).$
I would prefer to simplify the problem by treating $\gcd(a,b)$ grams as our unit of weight.
For example, if bars are either $80$ grams or $100$ grams, then since
$\gcd(80,100)=20$ I would like to introduce a unit of weight equal to
$20$ grams, so we now have bars whose weights are either $4$ units or $5$ units.
This simplifies the problem not only because the numbers are smaller, but also because we just have to purchase an integer amount of candy,
using the least integer which is greater than or equal to the amount (in our new units) that we wanted to buy,
and it guarantees that the weights of the candies (in the new units)
are relatively prime.
So in general, supposing we wanted to buy $x$ grams of candy
consisting of bars of $a$ grams or $b$ grams, we write
\begin{align}
u &= \frac{a}{\gcd(a,b)}, \\
v &= \frac{b}{\gcd(a,b)}, \\
n &= \left\lceil\frac{x}{\gcd(a,b)}\right\rceil. \\
\end{align}
As a result, $\gcd(u,v)=1,$ that is, $u$ and $v$ are relatively prime.
Now it is a well-known fact that if $n > uv - u - v,$
where $u$ and $v$ are relatively prime,
then we can buy candy bars of weights $u$ and $v$ so that their
total weight is $n$ exactly.
By understanding the proof of this fact (in an answer to an earlier question),
you should be able to devise an algorithm for finding the correct
number of candy bars of each type to buy in that case.
If $n \leq uv - u - v$ then the proof does not work, and indeed some
of those weights of candy may not be exactly achievable.
But for two fixed weights $u$ and $v,$ you can easily make a table of
the weights that are achievable and the number of bars of each type to buy
to achieve each weight.
Simply try each multiple of $u$ less than $uv - u - v,$ and for each
multiple $ku$ try each multiple of $v$ less than $(uv - u - v) - ku.$
For weights that cannot be achieved exactly, you simply use the next greater
weight that can be achieved.