-01 algorithm solution to a problem: the largest sub-columns and issues

0x01. Details title

Go to this specific point: poke me go

0x02. Variety of ideas

To seize the key topics, and sub-columns, so one kind of problem-solving approach of this violence occurs, yes, through all the sub-columns to identify and among the largest.

The key is to walk the child column, assuming the left column of point a child does not move, keep moving right point in the process, constantly updated and the largest sub-columns, traversed until all the sub-columns.

The main function:

int main()
{
    int a[100000];
    int k;
    scanf("%d",&k);
    int i;
    for(i=0;i<k;i++)
        scanf("%d",&a[i]);
     printf("%d",MaxSubseqSum1(a,k));
}

Method One: violent problem-solving O (n2)

int MaxSubseqSum1(int*a,int k)
{
    int i,j,max,temp;
    temp=max=0;
    for(i=0;i<k;i++)
    {
        temp=0;
        for(j=i;j<k;j++)
        {
            temp+=a[j];
            if(temp>max)
            {
                max=temp;
            }
        }
    }
    return max;
}

Point to note is that each time you begin to move the left point, it is necessary to reset the temp to zero.

Perfect by:

Although it passed, but it takes a final test point is still too long.

This approach began to improve.

Praying columns and found that when the maximum value of the sub-columns if the current calculation and is negative, then for the newly added elements, it will only become increasingly fewer, then, we can reset the temp, again counted the current sub-columns, the equivalent of constantly updated, and max, the maximum has been saved before, you can still do not need to consider the larger question of whether before.

Method two: Online Processing O (n)

int MaxSubseqSum2(int*a,int k)
{
    int i,max,temp;
    temp=max=0;
    for(i=0;i<k;i++)
    {
        temp+=a[i];
        if(temp>max)
        {
            max=temp;
        }
        else if(temp<0)
        {
            temp=0;
        }
    }
    return max;
}

Perfect to solve the problem.

Published 51 original articles · won praise 36 · views 1354

Guess you like

Origin blog.csdn.net/ATFWUS/article/details/104491238