# Preparation Evaluation -Editorial

Difficulty
Easy

Prerequisite
Observation

Explanation

Case 1: A[i] > A[j] and i > j
|A[i] - A[j]| = A[i] - A[j]
|i -j| = i - j

hence, f(i, j) = (A[i] + i) - (A[j] + j)

Case 2: A[i] < A[j] and i < j
|A[i] - A[j]| = -(A[i]) + A[j]
|i -j| = -(i) + j

hence, f(i, j) = -(A[i] + i) + (A[j] + j)

Case 3: A[i] > A[j] and i < j
|A[i] - A[j]| = A[i] - A[j]
|i -j| = -(i) + j

hence, f(i, j) = (A[i] - i) - (A[j] - j)

Case 4: A[i] < A[j] and i > j
|A[i] - A[j]| = -(A[i]) + A[j]
|i -j| = i - j

hence, f(i, j) = -(A[i] - i) + (A[j] - j)

Note that case 1 and 2 are equivalent and so are case 3 and 4 and hence we can design our algorithm only for two cases as it will cover all the possible cases.

``````1. Calculate the value of A[i] + i and A[i] – i for every element of the array while traversing through the array.
2. Then for the two equivalent cases, we find the maximum possible value. For that, we have to store minimum and maximum values of expressions A[i] + i and A[i] – i for all i.
3. Hence the required maximum absolute difference is maximum of two values i.e. max((A[i] + i) – (A[j] + j)) and max((A[i] – i) – (A[j] – j)). These values can be found easily in linear time.
a. For max((A[i] + i) – (A[j] + j)) Maintain two variables max1 and min1 which will store maximum and minimum values of A[i] + i respectively. max((A[i] + i) – (A[j] + j)) = max1 – min1
b. For max((A[i] – i) – (A[j] – j)). Maintain two variables max2 and min2 which will store maximum and minimum values of A[i] – i respectively. max((A[i] – i) – (A[j] – j)) = max2 – min2
``````
Author's Solution
``````#include<bits/stdc++.h>
#define ll long long
#define io ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL)
using namespace std;
#define N 1000000
#define limit 10000
#define mod 1000000007
#define pb push_back

template <typename T>
void print(T x){cout<<x<<"\n";}
template <typename T1, typename T2>
void print2(T1 x,T2 y){cout<<x<<" "<<y<<"\n";}
template <typename T1, typename T2,typename T3>
void print3(T1 x, T2 y,T3 z){cout<<x<<" "<<y<<" "<<z<<"\n";}

int maxArr(vector<int> &A) {
int max1=INT_MIN,min1=INT_MAX;
int max2=INT_MIN,min2=INT_MAX;
int n=A.size();

for(int i=0;i<n;i++)
{
max1=max(max1,A[i]+i);
min1=min(min1,A[i]+i);
max2=max(max2,A[i]-i);
min2=min(min2,A[i]-i);
}
int ans=(max1-min1,max2-min2);
return ans;
}

int main()
{
ll test_case;
cin>>test_case;
//test_case=1;
while(test_case--)
{
ll n;
cin>>n;

vector<int> arr(n);
for(int i=0;i<n;i++) cin>>arr[i];

print(maxArr(arr));
}
}
``````