#include<iostream>
#include<stdlib.h>
#include<time.h>
#include<vector>
using namespace std;
struct MyStruct
{
int low=0;
int high=0;
int sum=0;
};
//这个函数寻找跨域mid的最大子数组
MyStruct find_cross(int a[],int low,int high,int mid)
{
int l_sum=-100000, r_sum=-100000;//左边最大,右边最大,这里应该取负无穷s
int sum=0;//记录左右的和
MyStruct res;
for (int i = mid; i >= low; i--)
{
sum += a[i];
if (sum > l_sum)
{
l_sum = sum;
res.low = i;
}
}
sum = 0;
for (int i = mid+1; i <= high; i++)
{
sum += a[i];
if (sum > r_sum)
{
r_sum = sum;
res.high = i;
}
}
res.sum = l_sum + r_sum;
return res;
}
MyStruct find(int a[], int low, int high)
{
int mid;
MyStruct res;
MyStruct left_sum, right_sum, cross_sum;
if (low == high)
{
res.low = low;
res.high = high;
res.sum = a[low];
return res;
}
else
{
mid = (low + high) / 2;
left_sum = find(a, low, mid);//找到左边的最大子数组
right_sum = find(a, mid + 1, high);//找到右边的最大子数组
cross_sum = find_cross(a, low, high, mid);//找到跨越mid的最大子数组
}
//返回三者最大的
if (left_sum.sum > right_sum.sum)
{
if (left_sum.sum > cross_sum.sum)
{
return left_sum;
}
else
{
return cross_sum;
}
}
else
{
if (right_sum.sum > cross_sum.sum)
{
return right_sum;
}
else
{
return cross_sum;
}
}
}
int main()
{
MyStruct res;
int a[] = { 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7 };
res = find(a, 0, 15);
cout << res.low << "+" << res.high << "+" << res.sum << endl;
system("pause");
}
运行结果
7+10+43