求最大连续子序列之和的线性算法 c# 数据结构

来源:互联网 发布:手机淘宝怎么删评论 编辑:程序博客网 时间:2024/06/10 00:27

//控制台应用程序
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=0;//用来保存待比较的最大连续子序列之和
            int seqStart = 0, seqEnd = 0;
            for (int i = 0,j=0; j < sequence.Length; j++)//i用来标定序列起始位置
            {
                thisSum+=sequence[j];
                //每遍历一个新的值时,就将其累加到thisSum。后面将根据其值的正负来判断前面累加中的序列是否继续被认定为是最大连续
                //子序列的一部分。
                if (thisSum > maxSum)
                {
                    maxSum = thisSum;
                    seqStart = i;
                    seqEnd = j;
                }
                else if (thisSum < 0)
                {
                    i = j + 1;//重新从后面的数值开始寻找连续子序列之和最大的序列。
                    thisSum = 0;
                }
            }
            //输出结果

            Console.WriteLine("sequence[{0}]至sequence[{1}]的最大连续子序列之和最大:{2}", seqStart, seqEnd, maxSum);
            Console.Read();


        }
    }
}

原创粉丝点击