Google
 
Webcprogramming.com




An Affiliate of AIHorizon




Programming Challenge Solution

This can be solved in O(n) time using the following code that makes only a single pass over the array:

int max_sum(int *vector, int len)
{
    int best = 0, current = 0;
    int i = 0;
    for(i = 0; i < len; ++i)
    {
        current += *(vector + i);
        if(current < 0)
        {
            current = 0;
        }
        best = best > current ? best : current;
    }
    return best;
}


Download source

If you like this problem, you may like the book from which I originally learned of the problem, Programming Pearls by Jon Bentley.

-----
Interested in advertising with us?
Please read our privacy policy.
Copyright © 1997-2005 Cprogramming.com. All rights reserved.

Geodesy Designs