Given an array of numbers which has both positive and negative numbers, have to find the maximum sum of any of the sub-arrays of that array.
For example:
If the given input is :
5
1 2 3 -3 5
we have to see which is the sub-array that gives the maximum sum.
The possible sub-arrays and their sums are:
{1} sum=1
{1,2} sum=3
{1,2,3} sum=6
{2,3} sum=5
{1,3} sum=4
{2} sum= 2
{3} sum=3
{1,2,3,-3} sum=3
{2,3,-3} sum=2
{3,-3} sum= 0
{1,2,3,-3,5} sum=8
{2,3,-3,5} sum= 7
{3,-3,5} sum=5
{-3,5} sum=2
{5} sum=5
{-3} sum= -3
As, '8' is the largest sum, print it.
Implementation:
For example:
If the given input is :
5
1 2 3 -3 5
we have to see which is the sub-array that gives the maximum sum.
The possible sub-arrays and their sums are:
{1} sum=1
{1,2} sum=3
{1,2,3} sum=6
{2,3} sum=5
{1,3} sum=4
{2} sum= 2
{3} sum=3
{1,2,3,-3} sum=3
{2,3,-3} sum=2
{3,-3} sum= 0
{1,2,3,-3,5} sum=8
{2,3,-3,5} sum= 7
{3,-3,5} sum=5
{-3,5} sum=2
{5} sum=5
{-3} sum= -3
As, '8' is the largest sum, print it.
Implementation:
#include <stdio.h> #include <stdlib.h> int main(void) { int *a,n,i,max=0,curmax=0; /* Get the number of elements of the array */ scanf("%d",&n); /* Dynamically allocate memory block of n integers and store the starting address of the block in pointer 'a' */ a=(int*)malloc(sizeof(int)*n); /* Get the elements of the array */ for(i=0;i<n;i++) scanf("%d",(a+i)); /* Add the element one by one to curmax*/ for(i=0;i<n;i++) { curmax += *(a+i); /* If curmax value is less than zero, set curmax to zero */ if(curmax < 0) { curmax=0; } /* Else get the largest among curmax and max, store the result in max */ else { max=curmax>max?curmax:max; } } /* Print the maximum sum , which will be in variable 'max' */ printf("maximum sum is %d",max); return 0; }