链接:https://www.nowcoder.com/questionTerminal/f5805cc389394cf69d89b29c0430ff27
来源:牛客网
题目描述:
测试样例:
解题思路:;
1.maxleft与maxright一前一后遍历数组,各自存储遍历到的最大值(分别与各自的上一个存储的最大值比较)
2.计算maxleft与maxright的差值,返回到res中
3.最新的res与上一个res比较,留下最大值,最后返回的res则为左部分中的最大值减去右部分最大值的绝对值的最大值。
class MaxGap {
public:
int findMaxGap(vector<int> A, int n) {
// write code here
int maxleft = 0;
maxleft = A[0];
int maxright = 0;
int res = 0;
for(int i = 0; i < n-1; i++)
{
maxleft = max(maxleft,A[i]);
for(int j = i + 1; j < n; j++)
{
if(maxright < A[j])
maxright = A[j];
}
res = max(res,abs(maxleft-maxright));
maxright = 0;
}
return res;
}
};