The question is to find the maximum and minimum element in an array and return their difference. I referred to the editorial of the problem on GeeksforGeeks. I used the tournament method, in which we partition any array having more than two elements into 2 parts, and find the maximum and minimum of those two arrays, and then return the answer after comparing these final values. The official solution listed here , uses a struct pair. I wanted to do it using call by reference values.
Initially I tried to return 2 values with the function like:
int r1,r2= Sample(a,high,low)
That is wrong(as we can return only 1 value from the function) So I tried passing by reference like this:
void halfarrsol(int arr[], int low, int high, int &mi, int &ma){
int mid, min,max;
if(low==high){
mi=ma=arr[low];
}
if(high==low+1){
mi=arr[low], ma=arr[high];
if(arr[low]>arr[high]){
mi=arr[high];
ma=arr[low];
}
}
else {
mid=(low+high)/2;
halfarrsol(arr, low,mid,mi,ma);
int minl=mi, maxl=ma;
halfarrsol(arr, mid+1,high,mi,ma);
int minr=mi, maxr=ma, fin=minl;
if(minl>minr){
fin= minr;
}
int fax=maxl;
if(maxl<maxr){
fax=maxr;
}
mi= fin;
ma=fax;
}
}
The idea is that when I call the function, the final value of min and max (mi and ma) will be available. One obvious error that I think might be messing things up is the
halfarrsol(arr, low,mid,mi,ma);
int minl=mi, maxl=ma;
What I'm trying to here is store the obtained mi and ma vales(for this half array) in 'minl' and 'maxl' variables. Is this valid?
The overall code gives a segmentation error, and timeout: the monitored command dumped core error.
I'm not sure what exactly I'm messing up, or if this approach is completely wrong. I wanted to be able to solve this question without using a Struct Pair, and without using another class and creating an object.
There are also solutions like using a Tuple to store min and max values, but I considered them to be more applicable for when we have many return values, as here I am using 2 values only.
Is there any way to solve this problem recursively using call by reference?
If required you can view the driver code here