Home > Back-end >  Same test cases showing different answer
Same test cases showing different answer

Time:09-22

I have doubt regarding this min-max problem:

My code :

void miniMaxSum(vector<int> arr) {
    
sort(arr.begin(), arr.end()); 
int sum=0;
for(int i=0; i<5; i  )
sum  = arr[i];
cout<<sum-arr[4]<<" "<<sum-arr[0]<<endl;   

}

In other words:

void miniMaxSum(vector<int> arr) {
    
sort(arr.begin(), arr.end()); 

int min=0;
for(int i=0; i<4; i  )
min  = arr[i];
cout<<min<<" ";

int max=0;
for(int i=1; i<5; i  )
max  = arr[i];
cout<<max<<endl;
    
}

These code running successfuly for sample data 1 and 2, but when I submit my code, these test cases also showing as wrong output.

Can you please hint where this code wrong !

CodePudding user response:

Change int to long long according to given problem.

CodePudding user response:

int is a 32bit integer, the problem mentions that it's possible for the answer to bet greater than this. You will want to use a 64 bit integer (int64_t) for your vector and your max variables.

You should also switch to passing by reference instead of by value void miniMaxSum(vector<int> arr) { will copy the entire array, who void miniMaxSum(const vector<int>& arr) { will pass in a read only reference to the array without copying it.

  • Related