Description:
The goal in this problem is to find the minimum number of coins needed to change the input value (an integer) into coins with denominations 1, 5, and 10
The input consists of a single integer m.
1≤m≤103
Output the minimum number of coins with denominations 1, 5, 10 that changes m.
Code:
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Main
{
public static int CountChange(int m) {
if (m <= 0) return 0;
int[] denomenations = new int[]{10, 5, 1};
int change = 0;
for (int i : denomenations) {
while (m - i >= 0) {
m -= i;
change++;
}
}
return change;
}
public static void main (String[] args) throws java.lang.Exception
{
// edge cases
System.out.println(CountChange(0)); // 0
System.out.println(CountChange(-1)); // 0
System.out.println(CountChange(Integer.MIN_VALUE)); // 0
System.out.println(CountChange(Integer.MAX_VALUE));
System.out.println(CountChange(1)); // 1 = 1
System.out.println(CountChange(2)); // 2 = 1 + 1
System.out.println(CountChange(5)); // 1 = 5
System.out.println(CountChange(10)); // 1 = 10
System.out.println(CountChange(28)); // 6 = 10 + 10 + 5 + 1 + 1 + 1
}
}
Questions
- This seems exponential algorithm to me but what is the correct approach for finding the running time of this algorithm?
- I put some thoughts on testing strategies in this problem, since the input is integer I had few number of edge cases also the problem description doesn't cover edge cases (e.g.: maximum integer) but then also I thought to test it, is this the correct approach?
- For
m = 0
the algorithm works fine but still I gave a guard condition for readability, don't know if this is a good strategy. - I think that a better algorithm can be developed and suggestions are welcome.