题意:
给你两个长度相等的整数数组,返回下面表达式的最大值:
|arr1[i] - arr1[j]| + |arr2[i] - arr2[j]| + |i - j|
其中下标 i
,j
满足 0 <= i, j < arr1.length
。
思路:
根据数学思想,对于绝对值符号内的表达式( i > j ),共有四种可能
(1)arr1[i] > arr1[j] , arr2[i] > arr2[j]:arr1[i] - arr1[j] + arr2[i] - arr2[j] + i - j = ( arr1[i] + arr2[i] + i ) - ( arr1[j] + arr2[j] + j )
(2)arr1[i] > arr1[j] , arr2[i] < arr2[j]:arr1[i] - arr1[j] - arr2[i] + arr2[j] + i - j = ( arr1[i] - arr2[i] + i ) - ( arr1[j] - arr2[j] + j )
(3)arr1[i] < arr1[j] , arr2[i] > arr2[j]:- arr1[i] + arr1[j] + arr2[i] - arr2[j] + i - j = ( - arr1[i] + arr2[i] + i ) - ( - arr1[j] + arr2[j] + j )
(4)arr1[i] < arr1[j] , arr2[i] < arr2[j]:- arr1[i] + arr1[j] - arr2[i] + arr2[j] + i - j = ( - arr1[i] - arr2[i] + i ) - ( - arr1[j] - arr2[j] + j )
对于每一组(i,j),表达式的值必然属于上面四种情况的一种,并且所得到的值是四种情况中最大的,因此我们可以扫一遍数组,用当前值减去之前最小的值,再取一个最大值,就是所求的答案。
代码:
const int N=4e4+10;
class Solution {
public:
int v[N][4],pre[4];
int maxAbsValExpr(vector<int>& arr1, vector<int>& arr2) {
int n = arr1.size();
int ans=INT_MIN;
for(int i = 0;i < n;i++){
if(i==0){
pre[0]=arr1[i] + arr2[i] + i;
pre[1]=arr1[i] - arr2[i] + i;
pre[2]=-arr1[i] + arr2[i] + i;
pre[3]=-arr1[i] - arr2[i] + i;
}
else {
ans=max(ans,arr1[i] + arr2[i] + i - pre[0]); pre[0]=min(pre[0],arr1[i] + arr2[i] + i);
ans=max(ans,arr1[i] - arr2[i] + i - pre[1]); pre[1]=min(pre[1],arr1[i] - arr2[i] + i);
ans=max(ans,-arr1[i] + arr2[i] + i - pre[2]); pre[2]=min(pre[2],-arr1[i] + arr2[i] + i);
ans=max(ans,-arr1[i] - arr2[i] + i-pre[3]); pre[3]=min(pre[3],-arr1[i] - arr2[i] + i);
}
}
return ans;
}
};
原文地址:https://www.cnblogs.com/ljy08163268/p/11581975.html