# HackerRank - Making Candies

unknown
java
a year ago
2.1 kB
3
Indexable
Never
```class Result {

/*
* Complete the 'minimumPasses' function below.
*
* The function is expected to return a LONG_INTEGER.
* The function accepts following parameters:
*  1. LONG_INTEGER m
*  2. LONG_INTEGER w
*  3. LONG_INTEGER p
*  4. LONG_INTEGER n
*/

public static long minimumPasses(long m, long w, long p, long n) {
long candies = 0;
long turns = 0;
long minDays = calculateDays(m, w, n);
long turnsToBuy = calculateDays(m, w, p);
while (minDays - turnsToBuy > 1) {
candies += turnsToBuy * m * w;
long newMW = candies / p;
candies %= p;
if (m < w) {
long diff = w - m;
if (diff >= newMW) {
m += newMW;
} else {
newMW -= diff;
m += diff  + (newMW % 2 == 0 ? newMW / 2 : newMW / 2 + 1);
w += newMW / 2;
}
} else if (w < m) {
long diff = m - w;
if (diff >= newMW) {
w += newMW;
} else {
newMW -= diff;
w += diff  + (newMW % 2 == 0 ? newMW / 2 : newMW / 2 + 1);
m += newMW / 2;
}
} else {
m += newMW % 2 == 0 ? newMW / 2 : newMW / 2 + 1;
w += newMW / 2;
}
long days = calculateDays(m, w, n - candies);
if (minDays < days) {
break;
}
minDays = days;
turnsToBuy = calculateDays(m, w, p - candies);
}
return minDays + turns;
}

static long calculateDays(long m, long w, long n) {
try {
long prod = Math.multiplyExact(m, w);
return n % prod > 0 ? n / prod + 1 : n / prod;
} catch(ArithmeticException ignore) {
return 1;
}
}

}```