Logic and code in c++


#1

LOGIC :

Case 1 : A[i]>A[j] & i>j
f(i, j) = A[i]-A[j]+i-j = (A[i]+i)-(A[j]+j)

Case 2 : A[i]>A[j] & i<j
f(i, j) = A[i]-A[j]+j-i= (A[i]-i)-(A[j]-j)

Case 3 : A[j]>A[i] & i>j
f(i, j) = A[j]-A[i]+i-j = - [(A[i]-i) - (A[j]-j)]

Case 4 : A[j]>A[i] & i<j
f(i, j) = A[j]-A[i]+j-i= - [(A[i]+i)-(A[j]+j)]

We have to find the absolute value of f(i,j). Case 1 &4 and Case2&3 are similar if we have to find the absolute value. Now suppose there are only two cases that is 1 and 2.
Consider Case 1 –
To maximize f(i, j) we have to find the diff between the max and min value. Max value of A[i]+i and min value of A[j]+j. Lets suppose the difference is d1

Consider Case 2 –
To maximize f(i, j) we have to find the diff between the max and min value. Max value of A[i]-i and min value of A[j]-j. Lets suppose the difference is d2
and now we have to find the max value of d1 and d2.

CODE:

int Solution::maxArr(vector &A) {
int max_1 = INT_MIN,max_2 = INT_MIN,min_1=INT_MAX,min_2=INT_MAX ;
for(int i=0;i<A.size();i++)
{
if(A[i]+i>max_1)
max_1 = A[i]+i ;
if (A[i]+i<min_1)
min_1 = A[i]+i ;
if(A[i]-i>max_2)
max_2 = A[i]-i ;
if (A[i]-i<min_2)
min_2 = A[i]-i ;
}
return max((max_1-min_1),(max_2-min_2)) ;
}


#2

Very well explained bro


#3

thanks for kind explanation , very helpful – hare krishna jai shri krishna