Getting the optimal change in cents.

On one of my assignments I have to find the optimal change. For example, if I were to have 70 cents and had only quarters, dimes and pennies, the best way to receive change using less coins all together would be 2 quarters and 2 dimes (4 coins all together should be displayed).
All in all, I understand my assignment, however there is something I don't know how to do (or can't recall how to) and that is finding the the highest number in an array to use in a function and be able to compare it.
1
2
3
4
5
6
7
8
9
10
11
12

#include<iostream>
using namespace std;

//function in which amount = money, changeArray is the array where money is stored, 
//and numCoins the amount of coin types there are available in the array

int optimalChange(int amount, int * changeArray, int numCoins)
{

}


1
2
3
4
5
6
7
8
9
int main()
{
  int change[] = {1,10,25};    //pennies, dimes, and quarters.
  //(doesn't have to be in that order, if it's in any order is should still work.)
  
  cout << optimalChange(70, change, 3) << endl; //Should display 4 (2 quarters and 2 dimes)

  return 0;
}


What I'm stuck with, is that I don't remember how to get the highest number from the array that way I can compare it with the total amount when I'm building my function. Any idea on how to do that? Any help will be appreciated. Also, the function has to call itself recursively
Last edited on
What I would do is sort the array for highest to smallest(or just assign to it in that order). Then take away as many of those coins as you can (division).

For example I would make it an array of 25, 10, 1

Then we have the 70 cents as you mentioned

70 / 25 = 2.8 = 2 as an int it will floor which is what we want anyways

70 - 25 * 2 = 70 - 50 = 20
20 / 10 = 2
20 - 20 = 0

0 left so lets add up the coins 2 + 2 = 4

There might be a few bugs, but this is to give you a general idea of how to do it.
1
2
3
4
5
6
7
8
9
10
11
12
13
int optimalChange(int amount, int *changeArray, int numCoins)
{
    int coins = 0;
    int i = 0;
    while(amount && i < numCoins) //might not be able to get it perfectly with some coins
    {
        int possible = amount / changeArray[i];
        coins += possible;
        amount -= possible * changeArray[i++]; //increment i afterwards
    }

    return coins;
}
Topic archived. No new replies allowed.