This is kind of more generic question, isn\'t language-specific. More about idea and algorithm to use.
The system is as follows:
It registers small loans bet
If you take states as nodes of graph then you will be able to use shortest path algorithm to know the answer.