So I have written this code to minimize and maximize an expression using recursion. The code successfully runs and give the maximum value for the expression. However it fails to give the minimum value.
Where am I going wrong. The two variables minum
and maxum
stores INT_MAX and INT_MIN respectively.
What I am doing is generating all possibilities and whenever the result comes out to be minimum than what is already stored in minum we are updating it.
int parenthesis(string &S, int i, int j, int &minum, int &maxum)
{
if(i>j)
return 0;
if(i==j)
return S[i]-48;
int k, rightr, leftr, res;
for(k=i+1;k<j;k+=2)
{
// evaluate the left expression
leftr = parenthesis(S, i, k-1, minum, maxum);
// evaluate the right expression
rightr = parenthesis(S, k+1, j, minum, maxum);
if(S[k]=='/')
res = leftr / rightr;
else if(S[k]=='*')
res = leftr * rightr;
else if(S[k]=='-')
res = leftr - rightr;
else
res = leftr + rightr;
// update the minum and the maxum variable
if(res>maxum)
maxum = res;
if(res<minum)
minum = res;
}
return res;
}
int main()
{
string S;
int N, i, j, k;
cin>>S;
int minum=INT_MAX, maxum=INT_MIN;
j = S.size()-1;
parenthesis(S, 0, j, minum, maxum);
cout<<minum<<" "<<maxum;
return 0;
}
`
Where am I going wrong. Why does the code gives correct maxum but fails in giving minimum value. For example for 1+2*3+4*5
the expected output is Minimum value : 27, Maximum value : 105
but I am getting it as Minimum value : 3, Maximum value : 105
Note : Only single digit inputs are allowed.
EDIT : Even if someone can tell me the reason, why is not working that will be accepted as an answer