Maximum Absolute Difference
https://www.interviewbit.com/old/problems/maximum-absolute-difference/
Here we have f(i, j) = |A[i] - A[j]| + |i-j|
The 4 possible cases here are:
Case 1:
i>j and A[i] > A[j]:
f(i,j) can be rewritten as: (A[i]+i) - (A[j]+j)
Case 2:
i<j and A[i] < A[j]:
f(i,j) can be rewritten as: (A[j]+j) - (A[i]+i)
Case 3:
i<j and A[i] > A[j]:
f(i,j) can be rewritten as: (A[i] - i) - (A[j] - j)
Case 4:
i>j and A[i] < A[j]:
f(i,j) can be rewritten as: (A[j] - j) - (A[i] - i)
The 4 noticeable things to compute here are:
1. Maximum1 = max(A[i]+i)
2. Minimum1 = min(A[i]+i)
3. Maximum2 = max(A[i]-i)
4. Minimum2 = min(A[i]-i)
The function needs to return max(Maximum1 - Minimum1, Maximum2 - Minimum2)
Because this would go through all the possible cases, find the highest value of the function and return the best values for (A[i]+i) and (A[i]-i), and the max of these 2 would be the answer
int Solution::maxArr(vector<int> &nums) {
int mx1 = INT_MIN, mn1 = INT_MAX, mx2 = INT_MIN, mn2 = INT_MAX;
for(int i = 0; i < nums.size(); ++i){
// for eq 1
mx1 = max(mx1, nums[i]+i);
mn1 = min(mn1, nums[i]+i);
// for eq2
mx2 = max(mx2, nums[i]-i);
mn2 = min(mn2, nums[i]-i);
}
int ans1 = mx1 - mn1;
int ans2 = mx2 - mn2;
return max(ans1, ans2);
}
Comments
Post a Comment