C++求数组子数组和的最大值并将该子数组和最大值打印出来
#include <iostream>
using namespace std;
void GetMaxValue(int *pDatas, int len);
void main()
{
int datas1[6] = {1, -2, 3, 5, -3, 2};
//输出子数组最大值为8
//该子数组为:3 5;
GetMaxValue(datas1, 6);
//输出子数组最大值为:9
//该子数组为:3 5 -1 2
int datas2[6] = {0, -2, 3, 5, -1, 2};
GetMaxValue(datas2, 6);
//输出子数组最大值为:-2
//该子数组为: -2
int datas3[6] = {-9, -2, -3, -5, -3};
GetMaxValue(datas3, 5);
int tem;
cin >> tem;
}
void GetMaxValue(int *pDatas, const int len)
{
int max = -1000;
int sum = 0;
int k = 0;
int *result = new int[len];//该数组用于保存结果的子数组集合
int *tem = new int[len];//该数组用于辅助
for(int q = 0; q < len; q++)
{
result[q] = -100;
tem[q] = -100;
}
bool isChanged = false;
for(int i =0; i < len; i++)
{
sum =0;
for(int q =0; q < len; q++)
{
tem[q] = -100;
}
isChanged = false;
for(int j = i; j < len; j++)
{
sum += pDatas[j];
tem[j] = pDatas[j];
if(sum > max)
{
max = sum;
k = j;
isChanged = true;
}
}
if(isChanged)
{
for(int p = k + 1; p < len; p++)
{
tem[p] = -100;
}
for(int q = 0;q < len;q++)
{
result[q] = -100;
}
for(int f =0; f < len; f++)
{
if(tem[f] != -100 )
{
result[f] = tem[f];
}
}
}
}
cout << "子数组和最大值为:" << max << endl;
cout << "该子数组为:" << endl;
for(int i = 0;i < len; i++)
{
if(result[i] != -100)
{
cout << result[i] <<" ";
}
}
cout << endl;
}