# iterative money change code (algorithm)RSS

## 3 replies

Last post Oct 05, 2016 03:55 PM by PatriceSc

• kobosh

Member

17 Points

88 Posts

### iterative money change code (algorithm)

Hi I have tried unsuccessfully to code money change iteratively; help appreciated

```    static int recurChange(int money,int[] coins) {
int minCoins=  99999999;
if(money==0) return 0;
for(int c=0;c<coins.length;c++)
{
if(money>=coins[c]) {

int numCoins = recurChange(money - coins[c], coins);
if ((numCoins + 1) <minCoins)
minCoins=numCoins+1;

}
}
return minCoins;
}
/////////////////////////////////////////////////////////////////
static int iterativeChange(int money,int[] coins) {
int numCoins=0;
int minCoins=  99999999;
while ( money>0)
{
minCoins=  99999999;
for(int c=0;c<coins.length;c++)
{

if(money>=coins[c])
{

money=money-coins[c];
if(money==0)numCoins=0;
if ((++numCoins) <minCoins)
{
minCoins=numCoins;

}

}

}

}

return minCoins;

}
```

• PatriceSc

All-Star

40830 Points

13432 Posts

### Re: iterative money change code (algorithm)

Hi,

First I rarely provide ready to paste code. IMO it's best to understand and do things yourself rather than having others doing things for you.

So I would suggest here to use a tool such as https://msdn.microsoft.com/en-us/library/mt243867.aspx which allows to run your code line by line and watch variables values (and so keep an eye on how and when minCoins is changed). It will be very useful for all your debug needs.

Another option could be to exit the loop when done and count coins from 0. My understanding is that you have an array of all coins with their values in decreasing order and you want to know how many coins are needed to reach a given amount.

Edit:  the "high value" technique is rather when you want to find a min value. Here my understanding is that you just want a count ?

• kobosh

Member

17 Points

88 Posts

• PatriceSc

All-Star

40830 Points

13432 Posts