Yahoo Interview Question
Software Engineer / DevelopersGreedy approach won't work. I was asked the same question by Amazon and I gave him a greedy approach and the interviewer proved me wrong with a simple example.
Say,
coins = { 1, 10, 25 }
amount = 30
Greedy approach will choose 25 first and then five coins of value 1.
Dynamic will choose 3 10's.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class Coins {
Map<Integer, Integer> denoms = new HashMap<Integer, Integer>();
List<Integer> d = new ArrayList<Integer>();
public Coins() {
denoms.put(10, 5);
denoms.put(25, 5);
denoms.put(1, 5);
denoms.put(5, 5);
d.add(1);
d.add(5);
d.add(10);
d.add(25);
}
public int getCoins(int denom, int totalChange){
int count=1;
while(denom*++count <= totalChange){}
return --count;
}
public void getChange(Map<Integer, Integer> change, int totalChange){
if(totalChange <=0)return;
//for the totalChange, get the nearest denom...
for(int i=d.size()-1; i>=0;i--){
int aCoin = d.get(i);
if(aCoin<=totalChange){
int coins = getCoins(aCoin, totalChange);
change.put(aCoin,coins);
//.. Now how much more do we have left?
int changeSoFar = aCoin * coins;
int remChange = totalChange - changeSoFar;
getChange(change, remChange);
break;
}
}
}
public static void main(String[] args) {
Coins c = new Coins();
Map<Integer, Integer> chillar = new HashMap<Integer, Integer>();
c.getChange(chillar, 92 );
System.out.println(chillar);
}
}
import java.io.*;
import java.math.*;
public class Coins {
static int[] a;
public static void main(String[] args) throws Exception{
int amount = 30;
a = new int[amount+1];
System.out.println( count( amount ) );
}
static int count( int amount ) {
if (amount < 0) {
return Integer.MAX_VALUE;
} else if( amount == 0 ) {
return 0;
} else if( a[amount]>0 ) {
return a[amount];
} else {
a[amount] = Math.min( count( amount-25 ), Math.min( count( amount-10 ), count( amount-1 ) ) ) + 1;
return a[amount];
}
}
}
considering u have coins of 25, 10, and 1
Is this code correct ?
we can use dynamic programming to solve this problem, run time complexity should be
O(kN), where k = |denom| and N = amount, memory complexity is O(N)
Define f(i) = minimum number of coins needed to get amount of i
iterate j from 1 to amount
f(j) = 0 for j <= 0
f(j) = min{k in {denom}} ( j-k ) + 1; for j > 0
answer is f(amount)
yep, the person above is right.
- Igor S. October 05, 2010