数对之差的最大值

题目:在数组中,数字减去它右边的数字得到一个数对之差。求所有数对之差的最大值。例如在数组{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;
}


 

 

posted @ 2013-08-29 19:18  pangbangb  阅读(204)  评论(0编辑  收藏  举报