Skip to content

Commit f1c86ef

Browse files
committed
Added Kadanes Algorithm Maximum Subarray
1 parent 856adfb commit f1c86ef

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

Kadanes_Algorithm.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import java.util.*;
2+
3+
public class Main {
4+
public static long maxSubarraySum(int[] arr, int n) {
5+
long maxi = Long.MIN_VALUE; // maximum sum
6+
long sum = 0;
7+
8+
for (int i = 0; i < n; i++) {
9+
10+
sum += arr[i];
11+
12+
if (sum > maxi) {
13+
maxi = sum;
14+
}
15+
16+
// If sum < 0: discard the sum calculated
17+
if (sum < 0) {
18+
sum = 0;
19+
}
20+
}
21+
22+
if (maxi < 0) maxi = 0;
23+
24+
return maxi;
25+
}
26+
27+
public static void main(String args[]) {
28+
int[] arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4};
29+
int n = arr.length;
30+
long maxSum = maxSubarraySum(arr, n);
31+
System.out.println("The maximum subarray sum is: " + maxSum);
32+
33+
}
34+
35+
}
36+

0 commit comments

Comments
 (0)