算法题,做了近一天

原题出处,由July提供并解析,

http://blog.csdn.net/v_july_v/article/details/8701148

 

自己独立做,一开始方向有偏差。最后独立思路写了一个超容易出bug调了半天的O(n):

目前该程序至少在1000个以1~20长度以-20.0到20.0随机浮点数为元素的随机序列上和参考算法(穷举法)对比测试通过。

 

public static double MPCSolveQb2(this double[] seq, out int start, out int count)
{
    start = 0;
    count = seq.Length;

    if (seq.Length == 1)
    {
        return seq[0];
    }

    var maxp = 0.0;
    var maxpstart = 0;
    var maxpcount = 0;

    var maxn = 0.0;
    var maxnstart = 0;
    var maxncount = 0;

    var prevMax = double.MinValue;
    for (var i = 0; i <= seq.Length; i++)
    {
        var v = i == seq.Length ? 0 : seq[i];
        if (v > 0)
        {
            if (maxp <= 1)
            {
                maxp = v;
                maxpstart = i;
                maxpcount = 1;
            }
            else
            {
                if (v < 1 && maxp > prevMax)
                {
                    prevMax = maxp;
                    start = maxpstart;
                    count = maxpcount;
                }
                maxp *= v;
                maxpcount++;
            }

            if (maxncount > 0)
            {
                maxn *= v;
                maxncount++;
            }
        }
        else if (v < 0)
        {
            var oldmaxp = maxp;
            var oldmaxpstart = maxpstart;
            var oldmaxpcount = maxpcount;

            if (maxp > prevMax)
            {
                prevMax = maxp;
                start = maxpstart;
                count = maxpcount;
            }

            maxp = 0;
            maxpcount = 0;

            if (maxncount > 0)
            {
                var tmaxp = maxn * v;
                if (tmaxp > maxp)
                {
                    maxp = tmaxp;
                    maxpstart = maxnstart;
                    maxpcount = maxncount + 1;
                }
            }

            if (oldmaxpcount > 0 && oldmaxp > 1)
            {
                var tmaxn = oldmaxp*v;
                maxn = tmaxn;
                maxnstart = oldmaxpstart;
                maxncount = oldmaxpcount + 1;
            }
            else
            {
                maxn = v;
                maxnstart = i;
                maxncount = 1;
            }
        }
        else // v==0
        {
            if (maxp > prevMax)
            {
                prevMax = maxp;
                start = maxpstart;
                count = maxpcount;
            }
            maxn = 0;
            maxp = 0;
        }
    }
    return prevMax;
}


 

posted @ 2013-03-24 15:21  quanben  阅读(180)  评论(0编辑  收藏  举报