Skip to main content

Count number of coins needed




Write a method to return the minimum number of coins needed to match a given value. Assume coin denominations are 25, 10, 5, 1.

Example: If the value is 101, then we require four 25 cents coins and one 1 cent coin, so total is 5 coins.

public static int coinCount(int value){
int[] denominations = {25, 10, 5, 1};
int coinCount = 0;

for(int i = 0; i < denominations.length; i++){

if(value % denominations[i] == 0){
coinCount = coinCount + ( value/denominations[i]);
break;
}
if(value % denominations[i] > 0){
int r = value / denominations[i];
coinCount = coinCount + r;
value = value % denominations[i];
}
}

return coinCount;
}

Comments

Popular posts from this blog

Find second largest element in an array

Find second largest element in an unsorted array.               We can reach the solution in three ways.  Solution 1 Sort the array and return last but one element. We could use already existing sorting methods in JDK Arrays class and sort the array. public static int findSecondLargestV1( int [] array ){ if ( array . length == 0 || array . length < 2){ return -1; } Arrays.sort( array ); return array [ array . length - 2]; } Complexity: Since this solution depends on sorting, the complexity is equal to complexity of sorting algorithm, ie., O(n log n) Solution 2 public static int findSecondLargestV2( int [] array ){ if ( array . length == 0 || array . length < 2){ return -1; } int max = -1; for ( int i = 0; i < array . length ; i ++){ if ( array [ i ] > max ){ max = array [ i ]; } }...

Useful Java Related Resources

Java Tech Videos: http://www.techonvideo.com/category/programming/java/ Java Annotations: http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm http://download.oracle.com/javase/tutorial/java/javaOO/annotations.html