求给定数组的最大子数组

话说前天晚上被网易虐的也是够惨,3道编程题做出来两道,一个运行超时,一个通过率为70%。其实考的是动态规划之类的东西,只可惜我当时没有好好学。虽然牛客网服务器挂了导致考试延长一个小时,但这对我并没有什么实质帮助,不会还是不会呀。

今天开始啃《算法导论》,每天一个算法,坚持!

简单看了下分治这一节,照着书上的思想敲出了”给定数组的最大子数组”的代码,如下:

{
    if (left > mid || mid > right)
        return 0;
    int LeftSum = 0;
    int RightSum = 0;
    int LeftMaxSum = INT_MIN;
    int RightMaxSum = INT_MIN;
    int i;
    for (i = mid;i >= left;--i)
    {
        LeftSum += v[i];
        if (LeftSum > LeftMaxSum)
        {
            LeftMaxSum = LeftSum;
            *MaxLeft = i;
        }
    }
    for (i = mid + 1;i <= right;++i)
    {
        RightSum+= v[i];
        if (RightSum > RightMaxSum)
        {
            RightMaxSum = RightSum;
            *MaxRight = i;
        }
    }
    return LeftMaxSum + RightMaxSum;
}

int FindMaxSubArray(const vector<int>&amp; v, int left, int right,int* i,int* j)
{
    if (left > right)
        return 0;
    if (left == right)
    {
        *i = *j = left;
        return v[left];
    }
    int MaxLeft1, MaxRight1,MaxLeft2, MaxRight2,MaxLeft3, MaxRight3;
    int mid = left + (right - left) / 2;
    int LeftSum = FindMaxSubArray(v, left, mid, &amp;MaxLeft1, &amp;MaxRight1);
    int RightSum = FindMaxSubArray(v, mid + 1, right, &amp;MaxLeft2, &amp;MaxRight2);
    int MidSum = FindMidMaxSum(v, left, mid, right, &amp;MaxLeft3, &amp;MaxRight3);
    if (LeftSum >= RightSum &amp;&amp; LeftSum >= MidSum)
    {
        *i = MaxLeft1;
        *j = MaxRight1;
        return LeftSum;
    }
    else if (RightSum >= LeftSum &amp;&amp; RightSum >= MidSum)
    {
        *i = MaxLeft2;
        *j = MaxRight2;
        return RightSum;
    }
    else
    {
        *i = MaxLeft3;
        *j = MaxRight3;
        return MidSum;
    }
}

int calculateMax(vector<int> prices) 
{
    int i;
    vector<int> v;
    int left, right;
    for (i = 1;i < prices.size();++i)
    {
        v.push_back(prices[i] - prices[i - 1]);
        cout << prices[i] - prices[i - 1]<<" ";
    }
    cout << endl;
    int sum1=FindMaxSubArray(v, 0, v.size() - 1, &amp;left, &amp;right);
    int a = left;
    int b = right;
    int sum2 = FindMaxSubArray(v, 0, left - 1, &amp;left, &amp;right);
    left = a;
    right = b;
    int sum3 = FindMaxSubArray(v, right, v.size()-1, &amp;left, &amp;right);
    if (sum1 <= sum2 &amp;&amp; sum1 <= sum3)
    {
        if (sum2 < 0)
            return sum3;
        if (sum3 < 0)
            return sum2;
        return sum2 + sum3;
    }
    else if (sum2 <= sum1 &amp;&amp; sum2 <= sum3)
    {
        if (sum1 < 0)
            return sum3;
        if (sum3 < 0)
            return sum1;
        return sum1 + sum3;
    }
    else
    {
        if (sum1 < 0)
            return sum2;
        if (sum2 < 0)
            return sum1;
        return sum1 + sum2;
    }
}

代码的github地址