Skip to content

Commit 4f6e8b7

Browse files
author
Nitin Gupta
committed
Implementation of KadaneAlgorithm
1 parent 1d9b09a commit 4f6e8b7

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
public class KadanesAlgorithm {
2+
public static int maxSubArraySum(int[] nums) {
3+
int maxSoFar = nums[0];
4+
int currentMax = nums[0];
5+
6+
for (int i = 1; i < nums.length; i++) {
7+
8+
currentMax = Math.max(nums[i], currentMax + nums[i]);
9+
10+
maxSoFar = Math.max(maxSoFar, currentMax);
11+
}
12+
13+
return maxSoFar;
14+
}
15+
16+
public static void main(String[] args) {
17+
int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
18+
int maxSum = maxSubArraySum(nums);
19+
System.out.println("Maximum subarray sum is: " + maxSum);
20+
}
21+
}

0 commit comments

Comments
 (0)