最大子列和问题:输入第1行给出正整数K (≤100000);第2行给出K个整数,其间以空格分隔。
(1)在线处理
#include <iostream>
using namespace std;
int main()
{
int data[100000];
long int n;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> data[i];
}
int MaxSum = 0;
int TempSum = 0;
for (int i = 0; i < n; ++i)
{
TempSum += data[i];
if (TempSum > MaxSum)
{
MaxSum = TempSum;
}
else if (TempSum < 0)
{
TempSum = 0;
}
}
cout << MaxSum << endl;
return 0;
}
(2)分治
#include <iostream>
using namespace std;
int Max3(int a, int b, int c)
{
return a > b ? a > c ? a : c : b > c ? b : c;
}
int DivideAndConquer(int list[], int left, int right)
{
if (left == right)
{
if (list[left] <= 0)
{
return 0;
}
else
{
return list[left];
}
}
int MaxLeftSum, MaxRightSum;
int MaxLeftBorderSum = 0, MaxRightBorderSum = 0;
int center = ( left + right ) / 2;
MaxLeftSum = DivideAndConquer(list, left, center);
MaxRightSum = DivideAndConquer(list, center + 1, right);//从center + 1!!!!(错误历史)
int LeftBorderSum = 0, RightBorderSum = 0;
for (int i = center; i >= left; --i)
{
LeftBorderSum += list[i];
if (LeftBorderSum > MaxLeftBorderSum)
{
MaxLeftBorderSum = LeftBorderSum;
}
}
for (int i = center + 1; i <= right; ++i)
{
RightBorderSum += list[i];
if (RightBorderSum > MaxRightBorderSum)
{
MaxRightBorderSum = RightBorderSum;
}
}
return Max3(MaxRightBorderSum + MaxLeftBorderSum, MaxLeftSum, MaxRightSum);
}
/*int MaxSubseqSum3( int List[], int N )
{ /* 保持与前2种算法相同的函数接口 */
return DivideAndConquer( List, 0, N-1 );
}*/
int main()
{
int data[100000];
long int n;
cin >> n;
for (int i = 0; i < n; ++i)
{
cin >> data[i];
}
cout << DivideAndConquer(data, 0, n - 1) << endl;
return 0;
}