Maximum of absolute value Expression
The code is as follows :
class Solution {
public:
int get_result(vector<int> &nums){
int n = nums.size();
// we consider two more cases when i-j and j-i
int max1 = INT_MIN;
int max2 = INT_MIN;
int min1 = INT_MAX;
int min2 = INT_MAX;
int temp1,temp2;
for(int i=0;i<n;i++){
temp1 = nums[i]+i;
temp2 = nums[i]-i;
max1 = max(max1,temp1);
max2 = max(max2,temp2);
min1 = min(min1,temp1);
min2 = min(min2,temp2);
}
return max((max1-min1),(max2-min2));
}
int maxAbsValExpr(vector<int>& a, vector<int>& b) {
int n = a.size();
// we consider the cases b[i] > b[j] and b[j] > b[i]
// but we consider a[i] > a[j] always
vector<int> case1;
vector<int> case2;
for(int i=0;i<n;i++){
case1.push_back(a[i]+b[i]);
}
for(int i=0;i<n;i++){
case2.push_back(a[i]-b[i]);
}
// we return max of the two cases
return max(get_result(case1),get_result(case2));
}
};
Summarize
I was not ready for the problem directly working with four cases as opening the modulus and taking four cases considering i>j always but later I thought instead of considering i>j. I can consider a[i]>a[j] and still get away with it. and now I have to consider I<j and i>j both cases but that's fine. It's easier to encode and put on all the cases as above in the code. Try to understand the code.
We first took a[i]+b[i] as the case when second mod open with positive and a[i]-b[i] when second mod opens with negative. and we then add them with +i and -i one time total concluding with four cases covered. and we take maximum of all of the cases to obtain our maximum.