## Numeric Interview Question

Backend Developers**Country:**United States

Something like this would go well,(Java)

```
private static int calculate(int amount, int[] q, int[] c) {
int ret = 0;
int bal = 0;
for (int i = 0; i < n; i++) {
int n = amount / c[i];
int quantity = q[i] * n;
if (quantity > ret) {
ret = quantity;
bal = amount % c[i];
}
}
if (ret!=0&&bal!=0) ret+=calculate(bal,q,c);
return ret;
}
```

```
public int maxNumberChocolates(int amount, int[] quantities, int[] cost, int n) {
if(amount <= 0 || n < 0) {
return 0;
}
if(amount < cost[n]) {
return maxNumberChocolates(amount, quantities, cost, n-1);
} else {
return Math.max(
maxNumberChocolates(amount - cost[n], quantities, cost, n) + quantities[n],
maxNumberChocolates(amount, quantities, cost, n-1));
}
}
public int maxNumberChocolatesDpBottomUp(int amount, int[] quantities, int[] cost, int n) {
int[][] table = new int[amount+1][quantities.length+1];
for(int i=0; i <= amount; i++) {
for(int j=0; j <= quantities.length; j++) {
if(i == 0 || j == 0) {
table[i][j] = 0;
continue;
}
if(i < cost[j-1]) {
table[i][j] = table[i][j-1];
} else {
table[i][j] = Math.max(
table[i-cost[j-1]][j] + quantities[j-1],
table[i][j-1]);
}
}
}
return table[amount][quantities.length];
}
```

```
public int maxNumberChocolates(int amount, int[] quantities, int[] cost, int n) {
if(amount <= 0 || n < 0) {
return 0;
}
if(amount < cost[n]) {
return maxNumberChocolates(amount, quantities, cost, n-1);
} else {
return Math.max(
maxNumberChocolates(amount - cost[n], quantities, cost, n) + quantities[n],
maxNumberChocolates(amount, quantities, cost, n-1));
}
}
public int maxNumberChocolatesDpBottomUp(int amount, int[] quantities, int[] cost, int n) {
int[][] table = new int[amount+1][quantities.length+1];
for(int i=0; i <= amount; i++) {
for(int j=0; j <= quantities.length; j++) {
if(i == 0 || j == 0) {
table[i][j] = 0;
continue;
}
if(i < cost[j-1]) {
table[i][j] = table[i][j-1];
} else {
table[i][j] = Math.max(
table[i-cost[j-1]][j] + quantities[j-1],
table[i][j-1]);
}
}
}
return table[amount][quantities.length];
```

}

I could not solve it in the interview but solved it later. The idea is to find the unit cost of each shop. Then run a loop and fetch the min most unit cost that is affordable; until all the money is exhausted or no shop is affordable.

Code in Golang:

- git January 24, 2019