Buy 2 Get 1 Free codechef solution in c++
The "Buy 2 Get 1 Free" problem on CodeChef can be solved using the following C++ code:
#include <iostream>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int x, y, z;
cin >> x >> y >> z;
int totalBooks = x + y + z;
int minPrice = min(min(x, y), z);
int discount = minPrice / 2;
int finalPrice = totalBooks * minPrice - discount;
cout << finalPrice << endl;
}
return 0;
}
Explanation:
We start by including the necessary header file
iostream
to enable input/output operations.Inside the
main()
function, we declare an integer variablet
to store the number of test cases. We usecin
to read the value oft
from the user.We then enter a
while
loop that runst
times, as specified by the user.Inside the loop, we declare three integer variables
x
,y
, andz
to store the quantities of books in three categories. We usecin
to read the values ofx
,y
, andz
from the user.Next, we calculate the total number of books by adding
x
,y
, andz
together and store it in the variabletotalBooks
.We find the minimum quantity among
x
,y
, andz
using themin()
function and store it in the variableminPrice
.Since the offer is "Buy 2 Get 1 Free," we calculate the discount by dividing
minPrice
by 2 and store it in the variablediscount
.Finally, we calculate the final price by multiplying
totalBooks
withminPrice
and subtracting thediscount
. The result is stored in the variablefinalPrice
.We use
cout
to print the value offinalPrice
followed by a new line.The loop continues until all test cases are processed.
The
return 0;
statement ends the program.
This code solves the "Buy 2 Get 1 Free" problem by calculating the final price after applying the discount.