Max Contigous sum of array elements:
public class KadaneAlgorithm {
public static int getMaxSubArraySum(int[] arr) {
int maxSum = Integer.MIN_VALUE;
int currentSum = 0;
for (int i = 0; i < arr.length; i++) {
currentSum += arr[i];
maxSum = Math.max(maxSum, currentSum);
currentSum = Math.max(currentSum, 0);
}
return maxSum;
}
public static void main(String[] args) {
int[] arr = { -1, 3, 4, -2, 5, -7 };
int maxSum = getMaxSubArraySum(arr);
System.out.println("Maximum contiguous sum: " + maxSum);
}
}
Comments
Post a Comment