You're given an array containing both positive and negative
integers and required to find the sub-array with the largest
sum (O(N) a la KBL). Write a routine in C for the above.
Answers were Sorted based on User's Feedback
Answer / gopika
main()
{
int arr[100],sz,i,max,j,k,sum;
int start,end;
printf("\nEnter size :");
scanf("%d",&sz);
printf("\nEnter elements : ");
for(i=0;i<sz;i++)
scanf("%d",&arr[i]);
max=arr[0];
for(j=1;j<=sz;j++)
for(i=0;i<sz-j+1;i++)
{ sum=0;
for(k=0;k<j;k++)
{
sum+=arr[i+k];
if(sum>max)
{
max=sum;
start=i;
end=i+k;
}
}
}
printf("\nMax is %d\nStart %d\nend %d",max,start,end);
getch();
}
Is This Answer Correct ? | 0 Yes | 1 No |
Answer / monti
#include<iostream>
using namespace std;
int maxsum(int arr[], int size, int& strt_index, int&
end_index){
int max=0;
for(int i =0;i<size;i++){
max += arr[i];
strt_index = 0;
end_index = size-1;
}
int strt = 0;
int sum;
for(int i=0;i<size;i++){
sum =0;
for(int j = i; j<size; j++){
sum += arr[j];
if(sum >=max){
max = sum;
strt_index = strt;
end_index = j;
}
}
strt++;
}
return max;
}
int main(){
int strt, end;
int arr[10] = {0, 4, -5, 13, 8, -11, -2, 7, 9, -11};
int maxsub = maxsum(arr, 10, strt, end);
cout<<"\nMAX Sub Sum is : "<<maxsub;
cout<<"\nstarting index : "<<strt;
cout<<"\nEnding index : "<<end<<endl<<endl;
system("Pause");
return 0;
}
Is This Answer Correct ? | 0 Yes | 5 No |
Answer / sujan
#include<iostream>
#define SIZE 16
using namespace std;
int main()
{
int a[SIZE] = {-3, 5, -9, 4, -6, -24, -13, -14, -3, -20,
-45, -11, -2, -8, 1,10};
int temp[SIZE];
int j=0,sum=0;
for(int i=0;i<=SIZE;i++)
{
if(a[i]>0)
{
temp[j]=a[i];
j++;
}
}
cout<<"Sub-array:";
for(int k=0;k<j-1;k++)
{
sum+=temp[k];
cout<<temp[k]<<"\t";
}
cout<<"\n"<<"Sum:"<<sum<<endl;
system("pause");
}
Is This Answer Correct ? | 3 Yes | 31 No |
Why null pointer is used?
What are the restrictions apply to constructors and destructors?
What is this weird colon-member (" : ") syntax in the constructor?
Is c++ map a hash table?
How to implement is-a and has-a class relationships?
Write a program which uses Command Line Arguments
Is multimap sorted c++?
What is c++ programming language?
What is the importance of mutable keyword?
what is oops
Is eclipse good for c++?
What is endl c++?