Skip to content

Commit 94d8579

Browse files
committed
Added Kadane's Algorithm (Maximum Subarray Sum)
1 parent fe08e48 commit 94d8579

File tree

2 files changed

+28
-0
lines changed

2 files changed

+28
-0
lines changed
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
3+
public class KadanesAlgorithm {
4+
public static int maxSubArraySum(int[] nums) {
5+
if (nums == null || nums.length == 0) {
6+
throw new IllegalArgumentException("Input array cannot be null or empty");
7+
}
8+
int maxSoFar = nums[0];
9+
int currentMax = nums[0];
10+
for (int i = 1; i < nums.length; i++) {
11+
currentMax = Math.max(nums[i], currentMax + nums[i]);
12+
maxSoFar = Math.max(maxSoFar, currentMax);
13+
}
14+
return maxSoFar;
15+
}
16+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
package com.thealgorithms.dynamicprogramming;
2+
3+
public class TestKadane {
4+
public static void main(String[] args) {
5+
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
6+
System.out.println(maxSubArraySum(arr)); // Expected: 6
7+
}
8+
9+
private static int maxSubArraySum(int[] nums) {
10+
return KadanesAlgorithm.maxSubArraySum(nums);
11+
}
12+
}

0 commit comments

Comments
 (0)