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.

Answer Posted / 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



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What does iomanip mean in c++?

712


What it is and how it might be called (2 methods).

748


How is data hiding achieved in c++?

653


What is the default access level?

718


What is an html tag?

720






What is token c++?

664


Define a pdb file.

731


What is an adaptor class in c++?

698


How are the features of c++ different from c?

692


Evaulate: 22%5 a) 2 b) 4 c) 0

759


Tell me an example where stacks are useful?

675


What is the outcome of cout< a) 16 b) 17 c) 16.5

699


What is the use of namespace std in C++?

709


What is tellg () in c++?

835


Evaluate the following expression as C++ would do :8 * 9 + 2 * 5 a) 82 b) 79 c) 370 d) list

707