Wednesday, December 17, 2008

Max sum in the array

#include<iostream>
using namespace std;

#define _SIZE sizeof(array)/sizeof(array[0])
#define max(a,b) a>b ? a:b
int main()
{
    int array[] = { 0, 1, 2, -3, 5, 6, -5, 1, };
    int MaxSoFar = 0;
    int MaxCurrent = 0;
    for(int i = 0; i<_SIZE; ++i)
    {
        MaxCurrent = max(MaxCurrent+array[i], 0);
        MaxSoFar = max(MaxCurrent, MaxSoFar);
    }
    std::cout<<"Max sum in the array: "<< MaxSoFar<<"\n";
    return 0;
}

No comments:

Post a Comment