Making Candies – HackerRank Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.
Solutions of Algorithms Data Structures Hard HackerRank:
Here are all the Solutions of Hard , Advanced , Expert Algorithms of Data Structure of Hacker Rank , Leave a comment for similar posts
C++ Making Candies HackerRank Solution
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
bool check(ll machines, ll workers, ll price, ll target, ll rounds) {
if (machines >= (target+workers-1)/workers) return true;
ll cur = machines*workers;
rounds--;
if (rounds == 0) return false;
while (1) {
ll rem = target - cur;
ll rnds = (rem + machines*workers - 1) / (machines*workers);
if (rnds <= rounds) return true;
if (cur < price) {
rem = price - cur;
rnds = (rem + machines*workers - 1) / (machines*workers);
rounds -= rnds;
if (rounds < 1) return false;
cur += rnds * machines * workers;
}
cur -= price;
if (machines > workers) {
workers++;
} else {
machines++;
}
}
return false;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(0);
ll m, w, p, n;
cin >> m >> w >> p >> n;
ll a = 1, b = 1000000000000LL;
while (a < b) {
ll mid = (a + b) >> 1;
if (check(m, w, p, n, mid)) {
b = mid;
} else {
a = mid + 1;
}
}
cout << a << "\n";
return 0;
}
Python 3 Making Candies HackerRank Solution
def minimumPasses(m, w, p, n):
candy = 0
invest = 0
spend = sys.maxsize
while candy < n:
passes = (p - candy) // (m * w)
if passes <= 0:
mw = (candy // p) + m + w
half = math.ceil(mw / 2)
if m > w:
m = max(m, half)
w = mw - m
else:
w = max(w, half)
m = mw - w
candy %= p
passes = 1
candy += passes * m * w
invest += passes
spend = min(spend, invest + math.ceil((n - candy) / (m * w)))
return min(invest, spend)
Leave a comment below