Rk Reddy Bairi - 1 year ago 92

Java Question

working on a coding Bat question http://codingbat.com/prob/p191363 which has already many solutions here CondingBat Python puzzle results in "Timed out".

**My solution is marked as partially right. Trying to understand the problem.**

We want make a package of goal kilos of chocolate. We have small bars

(1 kilo each) and big bars (5 kilos each). Return the number of small

bars to use, assuming we always use big bars before small bars. Return

-1 if it can't be done.

makeChocolate(4, 1, 9) → 4 makeChocolate(4, 1, 10) → -1

makeChocolate(4, 1, 7) → 2

From what I understand, make chocolates method should use all available big bars to reach goal and then use small bars. Am returning 0 if big bars are already enough.

`public int makeChocolate(int small, int big, int goal) {`

if (small + big*5 < goal) return -1;

int smallNeeded = goal - big * 5;

if(smallNeeded <= 0) return 0;

return smallNeeded;

}

Answer Source

My understanding is something like this:

If not enough with big and small combined return `-1`

:

```
if((small + big * 5) < goal)
{
return -1;
}
```

If big are more than enough reduce the `goal`

by however many values of 5 (for big bars) then return the left over amount for how many small bars:

```
else if((big * 5) > goal)
{
return goal % 5;
}
```

If there is not enough big bars to make up the `goal`

reduce the value by all kilos taken up by big bars and take the remaining in small:

```
else
{
return goal - big * 5;
}
```