思路:
1、随机输入数组
2、求出数组之和a
3、用a与数组第一个数开始做和。如果数字小于a,那么舍弃该数;如果大于a,继续计算a与第一个数与第二个数之和,如果小于a舍弃这两个数,如果大于a,继续计算a与第一个数、第二个数、第三个数之和......直到计算的最后一个数为止。
4、与第3步步骤类似,只是从最后一个数开始计算,到第一个数为止。
5、求出最大子数组,输出该字数组数字,以及之和。
源代码:
#include <iostream>
#include <time.h>
using namespace std;
#define N 10
int a[N] ,b,b1,d,d1 = 0,jj = 0,k1 = 0;
int maxd = 0,maxd1 = 0 ,end1 = 0,end2=0;
void zheng(int& j,int k)
{
d = 0;
for (int i = j;i <= k;i++)
{
d += a[i];
if (d >= maxd)
{
maxd = d;
end1 = i;
}
if (b - d >= b)
{
b = b - d;
j++;
j = j + jj;
d = 0;
jj = 0;
}
else {
jj++;
}
}
}
void ni(int j,int &k )
{
d1 = 0;
for (int i = k;i >= j;i--)
{
d1 += a[i];
if (d1 >= maxd1)
{
maxd1 = d1;
end2 = i;
}
if (b1 - d1 >= b1)
{
b1 = b1 - d1;
k--;
k = k - k1;
d1 = 0;
k1 = 0;
}
else{
k1++;
}
}
}
void main()
{
int d = 0,d1 = 0;
int j = 0,k = N-1;
srand((unsigned int)time(0));
for (int i = 0;i < 10;i++)
{
a[i] = rand()%50 - 25;
cout << a[i] << " ";
b += a[i];
}
b1 = b;
cout << endl;
//去掉开头结尾的负数
for (int i = 0;i < N;i++)
{
if (a[i] < 0)
j++;
else
break;
}
for (int i = 0;i < N;i++)
{
if (a[N-1-i] < 0)
k--;
else
break;
}
int x = j,y = k;
zheng(j,k);
ni(x,y);
for (int i = j;i <= y;i++)
b += a[i];
if (maxd > b)
{
cout << "子数组为:";
for (int i = end2;i <= end1;i++)
cout << a[i] << " ";
cout << endl;
cout << "和为: " << maxd << endl;
}
else
{
cout << "子数组为:";
for (int i = j;i <= y;i++)
cout << a[i] << " ";
cout << endl;
cout << "和为: " << b << endl;
}
}