HackerRank ‘Chocolate Feast’ Solution

H
Short Problem Definition:

Little Bob loves chocolates, and goes to a store with $N in his pocket. The price of each chocolate is $C. The store offers a discount: for every M wrappers he gives to the store, he gets one chocolate for free. How many chocolates does Bob get to eat?

Link

Chocolate Feast

Complexity:

time complexity is O(N);

space complexity is O(1)

Execution:

Evaluate the number of wraps after each step. Do this until you have enough wraps to buy new chocolates.

Solution:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
 
int eatenChocolades(int availableCash, int price, int wrapperDiscount){
    int eaten = 0;
    int wraps = 0;
     
    wraps = eaten = availableCash/price;
     
    while (wraps >= wrapperDiscount){
        int newlyEaten = wraps/wrapperDiscount;
        eaten += newlyEaten;
        wraps %= wrapperDiscount;
        wraps += newlyEaten;
    }
     
     
    return eaten;
}
 
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */  
    int t,n,c,m;
    cin>>t;
    while(t--){
        cin>>n>>c>>m;
        int answer=0;
        answer = eatenChocolades(n,c,m);
        cout<<answer<<endl;
    }
    return 0;
}

About the author

Add comment

Archives

Categories