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.
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
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;
}
Can u guide with programming, data structure and algorithm certification final exam.
ReplyDeleteCan u guide with programming, data structure and algorithm certification final exam.
ReplyDeleteFinal Exam is bit tough .
Deletethere 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.
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
ReplyDeleteThank You
Thank you for putting some light on this matter from now on will try to explain my code.
Deleteplease explain your code with comments...
ReplyDelete\