mockers
Would you like to react to this message? Create an account in a few clicks or log in to continue.

maximum subarray

3 posters

Go down

maximum subarray Empty maximum subarray

Post  mnnit.rahul Tue Feb 03, 2009 3:05 am

find maximum sub array in an array


eg,, 5 4 -2 -6 12 5 -1

ans = 12+5=17

mnnit.rahul

Posts : 51
Join date : 2009-02-01

Back to top Go down

maximum subarray Empty Re: maximum subarray

Post  $corpion Tue Feb 03, 2009 11:00 pm

i don think 17 is correct ans for this...
its 5+4-2-6+12+5=18 Rolling Eyes
$corpion
$corpion

Posts : 25
Join date : 2009-01-30
Age : 37

Back to top Go down

maximum subarray Empty Re: maximum subarray

Post  Admin Wed Feb 04, 2009 12:43 am

reference:http://en.wikipedia.org/wiki/Kadane%27s_Algorithm

Code:
#include<iostream>
#include<string>


using namespace std;

/*
Kadane's Algorithm.

it scans through the array,
finding the maximum subarray that ends at that position
Note:such a subarray can be empty also.
*/

int main()
{
    int array[10] = {2, -1, -3, -4, 1, 2, -1, 5, 4,-1};
       
    int start,end,x;
    start = end =0;
    int s=1<<31;
    //1<<31 is the maximum possible negative value the int can hold,an approximation of negative infinity
    for (int i=0 ,j=0,t=0;
        i<10;i++)
    {
        t=t+array[i];
        if(t>s)
        {
              start=j;
              end=i;
              s=t;
        }
        if(t<0)
        {
              t=0;
              j=i+1;
        }
    }
   
    cout<<"sum = "<<s<<endl;
    for (int i=start;i<=end;i++)
    {
        cout<<array[i]<<" ";
    }
    cout<<endl;
    //cin>>start;
}

Admin
Admin

Posts : 47
Join date : 2009-01-29

https://mockers.forumotion.com

Back to top Go down

maximum subarray Empty Re: maximum subarray

Post  Sponsored content


Sponsored content


Back to top Go down

Back to top


 
Permissions in this forum:
You cannot reply to topics in this forum