Subarray of maximum Sum of a given Array O(n)!!!! (kadane algorithm)
#include<bits/stdc++.h>
using namespace std;
int main()
{
int n,i,j,k,sum,right,max_sum,s;
cout<<"enter the size of array : \n";
cin>>n;
int a[n];
for(i=0;i<n;i++)
cin>>a[i];
max_sum=-1;
right=-1;
sum=0;
for(i=0;i<n;i++)
{
sum+=a[i];
if(sum<0)
{
sum=0;
}
else if(sum>max_sum)
{
max_sum=sum;
right=i;
}
}
s=max_sum;
cout<<"The maximum sum will be: "<<max_sum<<endl;
//print the array from the right pos of max sum until...
//....max sum becomes zero.
cout<<"The subarray will be: ";
for(i=right;s!=0;i--)
{cout<<a[i]<<" ";
s-=a[i];}
//subarray is printed in reverse order....
}
Comments
Post a Comment