forked from MAYANK25402/Hactober-2023-1
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathKadane Algorithm
More file actions
28 lines (25 loc) · 807 Bytes
/
Kadane Algorithm
File metadata and controls
28 lines (25 loc) · 807 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
A Subarray witha sum less than 0 will always reduece our answer and so this type of subarray cannot be the part of the subarray with maximum sum.
import java.util.*;
import java.lang.*;
import java.io.*;
class Main {
public static int maximumSubarraySum(int[] arr) {
int n = arr.length;
int maxSum = Integer.MIN_VALUE;
for (int i = 0; i <= n - 1; i++) {
int currSum = 0;
for (int j = i; j <= n - 1; j++) {
currSum += arr[j];
if (currSum > maxSum) {
maxSum = currSum;
}
}
}
return maxSum;
}
public static void main(String args[]) {
// Your code goes here
int a[] = {1, 3, 8, -2, 6, -8, 5};
System.out.println(maximumSubarraySum(a));
}
}