VOOZH about

URL: https://www.geeksforgeeks.org/dsa/program-chocolate-wrapper-puzzle/

⇱ Program for Chocolate and Wrapper Puzzle - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Program for Chocolate and Wrapper Puzzle

Last Updated : 23 Jul, 2025

Given three values money, price, and wrap, the task is to find the total number of chocolates you can eat. Here money defines the total amount of money you have, price is the cost of buying a single chocolate and wrap defines the number of wrappers that can be returned to get one extra chocolate.

Examples:

Input: money = 16, price = 2, wrap = 2
Output: 15
Explanation: The price of a chocolate is 2. You can buy 8 chocolates for the amount 16. Then return 8 wrappers and get 4 more chocolates. Then you can return 4 wrappers and get 2 more chocolates. Finally, you can return 2 wrappers to get 1
more chocolate. So the total chocolates you eat will be 8 + 4 + 2 + 1 = 15.

Input: money = 15, price = 1, wrap = 3
Output: 22
Explanation: The price of a chocolate is 1. You can buy 15 chocolates for the amount 15. Then return 15 wrappers and get 5 more chocolates. Then you can return 3 wrappers and get 1 more chocolates. Finally, you can return 3 wrappers to get 1 more chocolate. So the total chocolates you eat will be 15 + 5 + 1 + 1 = 22.

[Naive Approach] Using Recursion : O(logw m/p) Time and O(logw m/p) Space

The idea is to recursively count the number of chocolates we can eat by returning the wrappers until no more wrappers are left or less than wrap wrappers are left.

Below is given the implementation:


Output
22

Time complexity: O(logw m/p), where w is the wrappers, m is money and p is the price of chocolate. Initially we have m / p chocolates, and in each iteration the number of wrappers are getting divided by w, thus the time complexity will be logarithmic.
Space complexity: O(logw m/p), considering the recursive call stack.

[Expected Approach] - Using Formula: O(1) Time and O(1) Space

In the above approach, it can be observed that after finding the initial number of chocolates, we recursively divide the number of chocolates by the number of wrappers required, until we are left with no wrapper or less than wrap wrappers i.e. ( ( choc / wrap + choc % wrap ) / wrap.
It can be analyzed that we can get the result by just reducing the values of chocolates and wrappers by 1 and then divide them to get the result i.e. ( choc - 1 ) / ( wrap - 1 ). 
Initially we have money / price chocolates, and later on by returning the wrappers we can have (chocolates - 1) / (wrap - 1) chocolates. Thus the total chocolates you can have is sum of these two numbers.

Below is given the implementation:


Output
22

Time Complexity: O(1)
Space Complexity: O(1)

Comment
Article Tags: