Skip to content

Commit 76c178a

Browse files
Merge pull request #1 from inimitable034/inimitable034-patch-1
Kadane's algorithm
2 parents dd5f5c4 + bb078fd commit 76c178a

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

Arrays/kadanes.java

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
// Java program for Kadane's Algorithm
2+
//
3+
class algo{
4+
5+
static void Kadanes(int a[], int size)
6+
{
7+
int max_so_far = Integer.MIN_VALUE,
8+
max_ending_here = 0,start = 0,
9+
end = 0, s = 0;
10+
11+
for (int i = 0; i < size; i++)
12+
{
13+
max_ending_here += a[i];
14+
15+
if (max_so_far < max_ending_here)
16+
{
17+
max_so_far = max_ending_here;
18+
start = s;
19+
end = i;
20+
}
21+
22+
if (max_ending_here < 0)
23+
{
24+
max_ending_here = 0;
25+
s = i + 1;
26+
}
27+
}
28+
System.out.println("Maximum contiguous sum is "
29+
+ max_so_far);
30+
System.out.println("Starting index " + start);
31+
System.out.println("Ending index " + end);
32+
}
33+
34+
35+
public static void main(String[] args)
36+
{
37+
int a[] = { 10, 16, -2, 8, 5, 9, -7, 3 };
38+
int n = a.length;
39+
Kadanes(a, n);
40+
}
41+
}
42+

0 commit comments

Comments
 (0)