给一个数组[a1,a2,a3....an],要求出令ai-aj有最大值,其中i<=j,要求时间和空间复杂度尽可能小,数组无序
int m = a[0], max_diff = 0;
for (int i = 1; i < n; ++i) {
if (m - a[i] > max_diff)
max_diff = m - a[i];
m = max(m, a[i]);
}
return max_diff;
//如果要求ai-aj绝对值最大的话,就用一个min记录最小值
int ma = a[0], min = a[0], max_diff = 0;
for(int i=1; i<n; i++){
if(ma - min > max_diff)
max_diff = max - min;
ma = max(ma, a[i]);
min = min(min, a[i]);
}