Skip to content

Commit

Permalink
Merge pull request #653 from ranaakash/master
Browse files Browse the repository at this point in the history
Kadanes algorithm properly implemented with guidelines  issue #651
  • Loading branch information
xlogix authored Nov 4, 2019
2 parents a000916 + 11a0490 commit c9d23be
Showing 1 changed file with 53 additions and 0 deletions.
53 changes: 53 additions & 0 deletions Algorithms/Arrays/Kadane/cpp-kadane'salgorithm-O(n)-2.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
///Lets do Kadane's Algorithm
///It is used to find largest sum in continous sub-array, for an array
///The following program also gives index of the array obtained ( for 0 based index)
///Explaination:https://hackernoon.com/kadanes-algorithm-explained-50316f4fd8a6

#include<iostream>
using namespace std;

int main()
{
int sumcurrent=0 , maxsum = 0,k=0,j=0 ,x = -1;
int n;
cout<<"Enter size of array"<<endl;
cin>>n;
int a[n];
cout<<"enter elements "<<endl;
for(int i=0;i<n;i++)
{
cin>>a[i];
}

for(int i=0;i<n;i++)
{
int temp = a[i];
///cout<<" sumcurrent+ a[i] is "<<sumcurrent+a[i]<<endl;
if((sumcurrent+a[i])>=0)
{
sumcurrent = sumcurrent +a[i];
}
else
{
sumcurrent = 0;
x = i+1;
}
if(sumcurrent>maxsum) ///Will only enter when when largest sum obtained
{
maxsum = sumcurrent ;
j = i;
if(x>=0)
{
k=x;
}
}

}

cout<<" maxsum is "<<endl;
cout<<maxsum<<endl;

cout<<" first and last index are "<<k<<" and "<<j<<endl;

return 0;
}

0 comments on commit c9d23be

Please sign in to comment.