Codechef Buy 2 Get 1 Free problem solution

In this Buy 2 Get 1 Free problem we have a sale going in the Showroom. for every 2 items a man pays for, he gets the third item for free. we have given that the cost of 1 item is X rupees. we need to find the minimum rupees required to buy at least T items.

Let's say we need 3 items where the cost of each item is 3 rupees. so the idea is about to pay for 2 items and get the third one for free. so the minimum required money to purchase 3 items is 3.2 = 6 rupees.

buy 2 get 1 free problem solution

Problem solution in C programming.

#include <stdio.h>

int main(void) {
	int i;
	scanf("%d",&i);
	while(i!=0)
	{
	    int n,x;
	    scanf("%d %d",&n,&x);
	    printf("%d\n", (n/3)*2*x + (n%3)*x);
	    i--;
	}
	return 0;
}


Here in the above code first we scan the number of test cases. and then in the while loop, we simply apply the logic (n/3)*2*x + (n%3)*x. here we apply this logic because we need to know about the minimum cost. so let's say a man needs to buy 3 things and each thing has a price of rupees 2. so according to logic first we find the (n/3)*2*x
that is (3/3)*2*2 = 4 so we got the minimum cost for buying the 3 things. but this logic is only applied for the even values. so for the odd values, we need to check (n%3)*x and add this value to the minimum cost. so here (3%3)*2 = 0*2 = 0. so the minimum value should be 4+0 = 4.

Problem solution in C++ programming.

#include <iostream>
using namespace std;
int main()
{
    int t; cin>>t;
    while(t--){
   int x; cin>>x;
   int y; cin>>y;
   cout<<(x%3+(x/3)*2)*y<<endl;
    }
    return 0;
}


Problem solution in Java programming.

import java.util.*;
import java.lang.*;
import java.io.*;

/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
	{
		// your code goes here
		Scanner sc = new Scanner(System.in);
		int t = sc.nextInt();
		while(t>0)
		{
		    t=t-1;
		    int n = sc.nextInt();
		    int x = sc.nextInt();
		    int m=0,k=0;
		    m=n/3;
		    k=n-m;
		    System.out.println((k*x));
		    
		}
		
	}
}


Problem solution in Python programming.

# cook your dish here
t=int(input())
for i in range(t):
    n,x=list(map(int,input().split()))
    a=n//3
    print((n-a)*x)


Here in the above logic first we read the number of test cases given by the user. and then we run the for loop for each and every test case and then read the values given by the user. after that, we store both the values for each test case in the n and x variable and then we apply the given below logic.

Let's say a man needs to buy 6 items. so first we divide it by 3.
a = 6//3 = 2 (here // means we only get the integer value not floating value)
and then we minus the a to n that is 6 - 2  = 4 and then we multiply with the cost for each thing. that is 4 *2 = 8. so he will need to pay 8 rupees.

Post a Comment

0 Comments