題目:在數組中,數字減去它右邊的數字得到一個數對之差。求所有數對之差的最大值。例如在數組{2, 4, 1, 16, 7, 5, 11, 9}中,數對之差的最大值是11,是16減去5的結果。
#include<iostream>
using namespace std;
void main()
{
int data[]={2, 4, 1, 16, 7, 5, 11, 9};
int length=sizeof(data)/sizeof(int);
int i;
int compare=data[length-1];
int max=0;
for(i=length-1;i>=0;i--)
{
int temp_sub;
if(data[i]>compare)
{
temp_sub=data[i]-compare;
if(temp_sub>max)
{
max=temp_sub;
}
}
else
{
compare=data[i];
}
}
cout<<max<<endl;
}