If i can exchange 3 empty bottles for one full bottle. Given that i have 18 full milk bottles initially, how many milk bottles can i drink?
Generalize this for 'n' bottles
--
I proposed a recursive solution to which the interviewer mentioned was incorrect.
int numBottles(int n)
{
if (n < 3) return n;
return n + numBottles(n/3)
}Then the interviewer mentioned that the solution is incorrect as we don't consider the fact that 'n' may not be divisible by 3 and their may be some remainder bottles as well which can be combined with the empty bottles if they are available from the next invocation of numBottles.
I modified my code as:
int numBottles(int n)
{
if (n < 3) return n;
int fullBottles = n;
int quotient = numBottles(n/3);
int remainder= n %3;
return n + quotient + numBottles((n/3)%3 + remainder);
}By this time, the time was over and we moved on to the next problem. Can anyone suggest if this is a right solution.