欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

最大子序列和

程序员文章站 2022-05-08 19:22:42
...

前提:输出不得为空数组。

一、分治法(O(nlgn))

int findmaxcrosssubarray(int* a,int low,int mid,int high)
{
    int leftsum =-10000,rightsum=-10000;
    int sum=0;
    int i,j;
    int maxleft,maxright;
    for(i=mid;i>=low;i--)
    {
        sum+=a[i];
        if(sum>leftsum)
        {
            leftsum=sum;
            maxleft=i;
        }
    }
    sum=0;
    for(i=mid+1;i<=high;i++)
    {
        sum+=a[i];
        if(sum>rightsum)
        {
            rightsum=sum;
            maxright=i;
        }
    }
    return leftsum+rightsum;
}

int findmaxsubarray(int* a,int low,int high)
{
    if(high==low)
        return a[low];
    int mid;
    mid=(low+high)/2;
    int leftsum,rightsum,crosssum;
    leftsum=findmaxsubarray(a,low,mid);
    rightsum=findmaxsubarray(a,mid+1,high);
    crosssum=findmaxcrosssubarray(a,low,mid,high);
    if(leftsum>=rightsum&&leftsum>=crosssum)
        return leftsum;
    else if(rightsum>=leftsum&&rightsum>=crosssum)
        return rightsum;
    else
        return crosssum;
}

二、动态规划(O(n))

int maxSubArray(int* nums, int numsSize) {
    int sum,tmp,i;
    tmp=0;
    sum=0;
    for(i=0;i<numsSize;i++)
    {
        tmp+=nums[i];
        if(tmp>sum)
            sum=tmp;
        else if(tmp<0)
            tmp=0;
    }
    if(sum==0)
    {
        sum=nums[0];
        for(i=1;i<numsSize;i++)
        {

            if(nums[i]>sum)
                sum=nums[i];

        }
    }
    return sum;
}