Help me in solving MAX_DIFF problem

My issue

In the TC when maximum tastiness of a dish is 5 and total tattiness of the two dishese is 6. Then how the exptected output is 4 instead of 1.

1
5 6

My code

#include <iostream>
using namespace std;

int main() {
	// your code goes here
	
	int n;
	cin>>n;
	
	while(n!=0){
	    int a, b;
	    cin>>a>>b;
	    if(a>b){
	        cout<<b<<endl;
	    } else if(a==b){
	        cout<<a<<endl;
	    } else if(a<b){
	        cout<<b-a<<endl;
	    }
	    n--;
	}
	return 0;
}

Learning course: Level up from 1* to 2*
Problem Link: CodeChef: Practical coding for everyone

obv max difference is 5
tastiness of dish 1: 5
tastiness of dish 2:1
so, output is 4.

I have pasted my correct code below .
include
using namespace std;

int main() {
int t;
int x,y,z;
cin>>t;
while(t–)
{
cin>>x>>y;
if(y<=x)
{
cout<<y<<endl;
}
else
{
cout<<2*x-y<<endl;
}

}
return 0;

}

1 Like

Thank you so much for the solution. But can you tell me the the logic for the (2*x-y) used in the else condition.

For both a<b , maximum possible difference is abs((a)-(b-a)). See for maximum possible difference one tastiness must be maximum and another tastiness must be minimum. Understand that there are 2 dishes which have tastiness t1 and t2 and both 0<t1,t2<=a.
and 0<(t1+t2)<=n, now when a<b, means sum is more than individual maximum value a, it means the maximum tastiness of a dish is a and minimum is (b-a) , so the maximum difference is
abs(a-(b-a)). similarly in the case when a=5 and b=6 , so maximum tastiness of a dish is 5 and minimum tastiness is (6-5)=1 , so the difference is 5-1=4

1 Like