题目:在数组中,数字减去它右边的数字得到一个数对之差。求所有数对之差的最大值。例如在数组{2, 4, 1, 16, 7, 5, 11, 9}中,数对之差的最大值是11,是16减去5的结果
考虑一个简单的情形:当数组只有两个数a[0],a[1]的时候,最大值当然是a[0]-a[1]了
当数组规模增大时,我们从数组末尾元素开始考虑,从数组元素右边的元素个数从1,2,3依次增加到size-1
设置一个元素cur_max记录该元素与右端元素之差的最大值
初始时从数组末尾开始,对于倒数第二个元素,cur_max为a[size-2]-a[size-1]
另外设置res保存返回值
相邻的两个元素i位置处的cur_max与i+1处的cur_max
因为i+1处与右边所有元素最大值为cur_max(设为a[i+1]-a[m],m>i+1),i处元素与i+1右边所有元素之差的最大值为a[i]-a[m]=a[i]-a[i+1]+cur_max,另外还需考虑a[i]-a[i+1],即i处元素与右边所有元素之差的最大值为
cur_max=max(cur_max+a[i]-a[i+1],a[i]-a[i+1])
#include<iostream>
using namespace std;
int max_diff(int *a,int size){
if(size<2)
return 0;
int res = a[size-2]-a[size-1];
int temp;
//max difference of current number substracts
//number on its right
int cur_max=res;
for(int i=size-3;i>=0;i--){
temp = a[i]-a[i+1];
cur_max = max(temp,temp+cur_max);
res = max(cur_max,res);
}
return res;
}
int main(){
int A[]={2, 4, 1, 16, 7, 5, 11, 9};
cout<<max_diff(A,8)<<endl;
return 0;
}