Wednesday 27 January 2016

Largest sum of all contiguous subarrays

Write an efficient C program to find the largest sum of contiguous subarray within an one-dimensional array of integers. A contiguous subarray of an array is defined as the sequence of elements that are in any continuous set of indices that are valid within an array.

Lets take an example of an array
{5,-3, 4}. Possible contiguous subarray combinations are {5}, {-3}, {4}, {5,-3}, {-3,4} and {5,-3,4}. Note that {5,4} is not a valid subarray as the indices of 5 and 4 are not continuous.
The contiguous subarray  {5,-3,4} has the largest sum 6.

Input Constraints:
First line : array size (N), where 1<= N<=100
Second line : N integers separated by spaces
where each number Ni satisfies
-10000 <= Ni <=10000
  
Output Constraints:

Single integer SUM which is the largest sum of all possible contiguous subarrays.
solution -:
#include<stdio.h> int a[200]={0},n,ni=-10000; int sub(); int main() { int i;scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d",&a[i]); if(ni<a[i]) ni=a[i]; } for(i=2;i<=n;i++) { ni=sub(a,i);} printf("%d",ni); return 0; } int sub(int a[],int b) {int j,i,sum=0; for(i=0;i<n;i++) { for(j=i;j<=b+i;j++) sum=sum+a[j]; if(sum>ni) ni=sum; sum=0; } return ni; }

6 comments:

  1. Can u guide with programming, data structure and algorithm certification final exam.

    ReplyDelete
  2. Can u guide with programming, data structure and algorithm certification final exam.

    ReplyDelete
    Replies
    1. Final Exam is bit tough .
      there are three question. Easy -medium-hard.
      you have specified amount of time. You can switch between any program at any time .
      however I simply don't know any program but you should have your tree,graph and matrix question pretty strong.

      Delete
  3. First of all thank You for posting the logic in the form of a program. But i guess that a little explanation of what you have done will give it a better understanding especially for the aspirants like us
    Thank You

    ReplyDelete
    Replies
    1. Thank you for putting some light on this matter from now on will try to explain my code.

      Delete
  4. please explain your code with comments...
    \

    ReplyDelete