#include<iostream.h>
//分治理法求解
int max_diff(int a[],int low,int high)//max min 返回最大值与最小值;
{
if(high-low<=0)
{
return -1000;//返回一个值就行,无用很小的值
}
int mid=(low+high)/2;
int leftDiffer=max_diff(a,low,mid);
int rightDiffer=max_diff(a,mid+1,high);
int maxleft=a[low];
int minright=a[mid+1];
int i=low+1;
int j=mid+2;
for(;i<=mid;i++)
{
if(a[i]>maxleft)
{
maxleft=a[i];
}
}
for(;j<=high;j++)
{
if(a[j]<minright)
{
minright=a[j];
}
}
int maxDIff=leftDiffer;
int crossDiff=maxleft-minright;
if(maxDIff<rightDiffer)
maxDIff=rightDiffer;
if(maxDIff<crossDiff)
maxDIff=crossDiff;
}
//动态规划解法max保存当前最大值,cur保存最大差值
int max_diff2(int a[],int len)
{
int max=a[0];
int cur=a[0]-a[1];
for(int k=2;k<len;k++)
{
if(a[k]>max)
max=a[k];
int tem=max-a[k];
if(tem>cur)
cur=tem;
}
return cur;
}
void main()
{
int a[]={2, 4, 1, 16, 7, 5, 11, 9};
int differ= max_diff(a,0,7);
cout<<"the differ is"<<differ<<endl;
differ=max_diff2(a,8);
cout<<"the differ is"<<differ<<endl;
}
数组中最大差(左边有序)
最新推荐文章于 2021-03-20 17:14:45 发布