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
What does iomanip mean in c++?
What it is and how it might be called (2 methods).
How is data hiding achieved in c++?
What is the default access level?
What is an html tag?
What is token c++?
Define a pdb file.
What is an adaptor class in c++?
How are the features of c++ different from c?
Evaulate: 22%5 a) 2 b) 4 c) 0
Tell me an example where stacks are useful?
What is the outcome of cout< a) 16 b) 17 c) 16.5
What is the use of namespace std in C++?
What is tellg () in c++?
Evaluate the following expression as C++ would do :8 * 9 + 2 * 5 a) 82 b) 79 c) 370 d) list