// 程序员面试题精选100题(61)-数对之差的最大值.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
using namespace std;
#define N 9
int max(int a,int b,int c)
{
if (a>b)
{
if (a>c)
{
return a;
}
else
return c;
}
else
{
if (b>c)
{
return b;
}
else
return c;
}
}
int divided(int *arr,int i,int j)//divide and conquer method from i to j
{
if (i==j)
{
return 0;
}
int mid=(i+j)/2;// into i==0 j==0 wrong
int m1,m2,m3;
m1=divided(arr,i,mid);
m2=divided(arr,mid+1,j);//mid + 1
int temp1=-1000,temp2=1000;
for (int k=i;k<=mid;k++)
{
if (arr[k]>temp1)
{
temp1=arr[k];
}
}
for (int k2=mid;k2<=j;k2++)
{
if (arr[k2]<temp2)
{
temp2=arr[k2];
}
}
m3=temp1-temp2;
return max(m1,m2,m3);
}
int sumOfArr(int* arr,int n)
{
int *diff = new int[n-1];
for (int i=0;i<n-1;i++)
{
diff[i]=arr[i]-arr[i+1];
}
int max=diff[0];
for (int j=1;j<n-1;j++)
{
if (diff[j-1]+diff[j]>diff[j])
{
diff[j]=diff[j-1]+diff[j];
}
if (max<diff[j])
{
max=diff[j];
}
}
return max;
}
int dynamicP(int* arr, int n)
{
int *diff=new int[n];//diff[i]是以数组中第i个数字为减数的所有数对之差的最大值
diff[1]=arr[0]-arr[1];
int max=diff[1];
for (int i=2;i<n;i++)
{
if (diff[i-1]+arr[i-1]-arr[i]>arr[i-1]-arr[i])
{
diff[i]=diff[i-1]+arr[i-1]-arr[i];
}
else
diff[i]=arr[i-1]-arr[i];
if (max<diff[i])
{
max=diff[i];
}
}
return max;
}
int _tmain(int argc, _TCHAR* argv[])
{
int arr[]={20,-4,12,10,16,-7,5,1,9};
int (*diff)[N] = new int[N-1][N];// how to create dynamic array
int maxv=0;
for (int i=0;i<N-1;i++)
{
diff[i][i+1]=arr[i]-arr[i+1];
if (diff[i][i+1]>maxv)
{
maxv=diff[i][i+1];
}
}
cout<<"when step is "<<1<<" max is "<<maxv<<endl;
int stepnum=N-1;
for (int step=2;step<=stepnum;step++)
{
for (int j=0;j<N-step;j++)
{
diff[j][j+step]=diff[j][j+1]+diff[j+1][j+step];
if (diff[j][j+step]>maxv)
{
maxv=diff[j][j+step];
}
}
cout<<"when step is "<<step<<" max is "<<maxv<<endl;
}
cout<<"dynamic programming with two dimensions array is "<<maxv<<endl;
//
cout<<"divide and conquer method is "<<divided(arr,0,N-1)<<endl;
//
cout<<"sum of the sub array method is "<<sumOfArr(arr,N)<<endl;
//
cout<<"dynamic programming with one dimensions array is "<<dynamicP(arr,N)<<endl;
system("pause");
return 0;
}
程序员面试题精选100题(61)-数对之差的最大值
最新推荐文章于 2021-07-23 23:16:47 发布