We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
@ansonete: This is indeed the cleanest solution, and the logic is simple: for every m wrappers you get a candy, candy = wrapper, i.e. for every m wrappers you get 1 wrapper back. Thus, the actual "wrapper price" of one candy is (m - 1) rather than m. Now, dividing your original number of wrappers by the "reduced price" is unfair - you still have to pay "full price" (i.e. full m) for the very first "exchange candy". Thus, let us first put m aside to make sure we get our first free candy. So the amount of wrappers to divide by reduced price is (boughtCandy - m). Now, the total number of candies is:
boughtCandy = money / cost
total = boughtCandy + 1 + (boughtCandy - m) / (m - 1)
where 1 is the candy we bought for the m we put aside in the first place. This can be simplified as follows:
total = boughtCandy + (m - 1)/(m - 1) + (boughtCandy - m) / (m - 1)
= boughtCandy + (m - 1 + boughtCandy - m) / ( m - 1 )
= boughtCandy + (boughtCandy - 1)/(m - 1)
Et voila!
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Chocolate Feast
You are viewing a single comment's thread. Return to all comments →
@ansonete: This is indeed the cleanest solution, and the logic is simple: for every m wrappers you get a candy, candy = wrapper, i.e. for every m wrappers you get 1 wrapper back. Thus, the actual "wrapper price" of one candy is (m - 1) rather than m. Now, dividing your original number of wrappers by the "reduced price" is unfair - you still have to pay "full price" (i.e. full m) for the very first "exchange candy". Thus, let us first put m aside to make sure we get our first free candy. So the amount of wrappers to divide by reduced price is (boughtCandy - m). Now, the total number of candies is:
boughtCandy = money / cost
total = boughtCandy + 1 + (boughtCandy - m) / (m - 1)
where 1 is the candy we bought for the m we put aside in the first place. This can be simplified as follows:
total = boughtCandy + (m - 1)/(m - 1) + (boughtCandy - m) / (m - 1)
= boughtCandy + (m - 1 + boughtCandy - m) / ( m - 1 )
= boughtCandy + (boughtCandy - 1)/(m - 1)
Et voila!