using System;
using System.Collections.Generic;
using System.Text;
namespace 求最大连续子序列之和的平方算法
{
class Program
{
static void Main(string[] args)
{
//自定义一个测试数组
int[] sequence ={ 56, -98, 2, -6, 100, 5, 88, -300, -9, 44 };
int maxSum = 0;//用来保存最大连续子序列的和
int thisSum;//用来保存待比较的连续了序列之和
int seqStart=0, seqEnd=0;
//平方算法相比较立方算法省掉了一个嵌套循环,应该是运行时间降低了
for (int i = 0; i < sequence.Length; i++)
{
thisSum = 0;
for (int j = i; j < sequence.Length; j++)
{
thisSum += sequence[j];
if (thisSum > maxSum)
{
maxSum = thisSum;
seqStart = i;
seqEnd = j;
}
}
}
//输出结果
Console.WriteLine("sequence[{0}]至sequence[{1}]的最大连续子序列之和最大:{2}", seqStart, seqEnd, maxSum);
Console.Read();
}
}
}