I think this problem works best iteratively, forward. I am going to split the solution points. If I wrote one formula, would I use ?: All results are given in Kg.
The first question is whether there is enough grain, and cart capacity, to justify an initial trip from oasis to town. The camel would eat FD, so if FD >= min(N,C) the answer is 0 If FD < min(N,C), the net amount transferred on the initial oasis to town trip is min(N,C)-FD. The camel is now in town, the remaining grain pile is N-min(N,C), and we have to decide whether to send it back again. If C <= 2FD, no round trip can be profitable. Otherwise consider a round trip with at least C remaining at the oasis. That gains net C-2FD (FD put in the cart in town to keep the camel fed getting to the oasis, C-FD remaining in the cart when it gets back to town). If N>C, we can do floor((NC)/C) of those round trips, net gain floor((NC)/C)*(C-2FD). After doing the initial run and any full cart round trips, the remaining grain pile is N%C, the remainder on dividing N by C. If N%C > 2FD it is worth doing a final trip to empty the grain pile, with an additional net gain of N%C-2FD.
source share