Largest Sum Contiguous Subarray

Largest Sum Contiguous Subarray
Write an C program to find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum.Logic is first add all contiguous element and store in an array.

#include<stdio.h>

int max(int a,int b)
{
if(a>=b)
return a;
else
return b;
}

main()
{

 int a[20],sum[20],i,j,k,n,add,max_add=0;

  printf("Enter Number Of Element in Array:\n");
  scanf("%d",&n);

  printf("Read Array Element From User:");
   for(i=0;i<n;i++)
    {
      scanf("%d",&a[i]);
    }

    for(i=0;i<n-1;i++)
     {
      j=i;
      k=i+1;
       sum[i]=a[j]+a[k];
     }
      for(i=0;i<n;i++)
       {
       add=sum[i];
       for(j=i+1;j<n-1;j++)
         {
          add=add+sum[j];
         }
        max_add=max(add,max_add);
       }

   printf("%d\n",max_add );
}

Related Posts