Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 11a0490

Browse files
Kadanes algorithm properly implemented with guidelines
1 parent 9ef5eba commit 11a0490

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
///Lets do Kadane's Algorithm
2+
///It is used to find largest sum in continous sub-array, for an array
3+
///The following program also gives index of the array obtained ( for 0 based index)
4+
///Explaination:https://hackernoon.com/kadanes-algorithm-explained-50316f4fd8a6
5+
6+
#include<iostream>
7+
using namespace std;
8+
9+
int main()
10+
{
11+
int sumcurrent=0 , maxsum = 0,k=0,j=0 ,x = -1;
12+
int n;
13+
cout<<"Enter size of array"<<endl;
14+
cin>>n;
15+
int a[n];
16+
cout<<"enter elements "<<endl;
17+
for(int i=0;i<n;i++)
18+
{
19+
cin>>a[i];
20+
}
21+
22+
for(int i=0;i<n;i++)
23+
{
24+
int temp = a[i];
25+
///cout<<" sumcurrent+ a[i] is "<<sumcurrent+a[i]<<endl;
26+
if((sumcurrent+a[i])>=0)
27+
{
28+
sumcurrent = sumcurrent +a[i];
29+
}
30+
else
31+
{
32+
sumcurrent = 0;
33+
x = i+1;
34+
}
35+
if(sumcurrent>maxsum) ///Will only enter when when largest sum obtained
36+
{
37+
maxsum = sumcurrent ;
38+
j = i;
39+
if(x>=0)
40+
{
41+
k=x;
42+
}
43+
}
44+
45+
}
46+
47+
cout<<" maxsum is "<<endl;
48+
cout<<maxsum<<endl;
49+
50+
cout<<" first and last index are "<<k<<" and "<<j<<endl;
51+
52+
return 0;
53+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /