Maximum Sub Array Problem Brute Force

Hey Everyone !! :)

I wrote a program for finding the maximum sub array using brute force technique using two methods. The first one is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
void FindMaxSubArray::BruteForcen3()
{
    int i,j,k=0,c=0,s=0,as=-9999,l,h,N=n;
    for(i=0;i<n;i++)
    {
        for(j=0;j<N;j++)
        {
            for(k=j;k<=(j+c);k++)
                s+=A[k];
            if(s>as)
            {
                as=s;
                l=j+1;
                h=k;
            }
            s=0;
        }
        N--;
        c++;
    }
    cout << endl << "The Maximum SubArray of A[] is from " << 
         l << " to " << h <<" and it is " << as << endl;
}


This one's working correct. Now here's the other one:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
void FindMaxSubArray::BruteForcen3v2()
{
    int i=0,j=0,k=0,as=-9999,s=0,l=0,h=0;
    for(i=0;i<n;i++)
    {
        for(j=i;j<n;j++)
        {
            for(k=i;k<=j;k++)
                s=+A[k];
            if(s>as)
            {
                as=s;
                l=i+1;
                h=k;
            }
            s=0;
        }
    }
    cout << endl << "The Maximum SubArray of A[] is from " << 
         l << " to " << h <<" and it is " << as << endl;
}


Now this one isn't working correct and I can't seem to understand why. Yeah I know that there are better algorithms for finding the maximum sub array but I was getting started on this thing. Can anyone help me ?
Last edited on
1
2
3
4
5
 for(k=i;k<=j;k++)
                s=+A[k];
//should be
 for(k=i;k<=j;k++)
                s += A[k];

Also, if you're using for, you don't need to declare your vars before the loop:
 
for(size_t i = 0; i < MAX; ++i)
Ohhh.....i didn't see that. My mistake. I got it....thanks !! :)
Topic archived. No new replies allowed.