In the Kadane algorithm, only maximum sum value is printed. But if we need the sub array elements also to be printed. How to do that?
How to print subarray elements when using Kadane algorithm for maximum subarray
For that you can use a separate boolean array to store index of the elements that you are considering in subarray.
And after the code you can traverse that array and print value at that index if its true
kadanes algo with subarray …!!
#include
using namespace std;
int main()
{
int a[1000];
int temp_sum = 0 ,maxsum=0,i,j,n;
int left = 0, right = -1;
cin>>n;
for(i = 0 ; i < n ; i++)
cin>>a[i];
for(int j = 0 ; j <n ; j ++)
{
if(temp_sum < 0) // if adding negative no. making temp_sum negative than has to leave that subarray ..
{
temp_sum = 0;
left = j ;
}
temp_sum+=a[j]; // making temparory sum
if(temp_sum>maxsum) // update the max sum
{
maxsum=temp_sum;
right = j;
}
}
cout<<"\n max posssible sum is : " <<maxsum<<" for the given array .."<<endl;
for(int i = left ; i <=right ; i++)
cout<<a[i]<<" , ";
return 1;
}