Hello everybody ,
I have got this question from some website and felt i should put it in my blog under a new label "interview section "
As the question speaks out , we need to find out the maximum number of a sub array in a given array ( this sub array was containing positive and negative integers so the question makes sense).
to make it more clear , assume we have an array
example 1 :
{3,4,-1,0,8,3,4,10,32,-30,5} in this array the maximum sub array would be "57"
example 2 :
{3,4,-1,0,8,3,4,-20,32,-30,5}; in this array the maximum sub array would be "32" .
So we will try to write the program in a simplest form and with less complexity !
void main()
{
int i = 0;
int prev_max = 0;
int new_max = 0;
for (i = 0 ;i < 30; i ++)
{
new_max += array[i];
if(new_max < 0 )
new_max = 0;
else
{
if(prev_max < new_max)
prev_max = new_max;
}
}
printf("Max of a sub array is %d \n", prev_max);
}
{
int i = 0;
int prev_max = 0;
int new_max = 0;
for (i = 0 ;i < 30; i ++)
{
new_max += array[i];
if(new_max < 0 )
new_max = 0;
else
{
if(prev_max < new_max)
prev_max = new_max;
}
}
printf("Max of a sub array is %d \n", prev_max);
}
Above logic would find out the maximum of a sub array with o(n) complexity .
I shall come up with such simple yet interesting questions on a regular basis.
No comments:
Post a Comment