-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkadanesalgorithm.java
51 lines (42 loc) · 1.27 KB
/
kadanesalgorithm.java
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
public class kadanesalgorithm {
public static void kadanes(int numbers[]) {
// int ts1 = 0;
int maxsum = Integer.MIN_VALUE;
int curr = 0;
for (int i = 0; i < numbers.length; i++) {
int start = i;
for (int j = i; j < numbers.length; j++) {
int end = j;
curr = 0;
for (int k = start; k <= end; k++) {
if(curr<0)
curr = 0;
curr += numbers[k];
}
System.out.println(curr);
if (maxsum < curr) {
maxsum = curr;
}
}
}
System.out.println("max is: " + maxsum);
}
public static void kadanesalgo(int numbers[]) {
//we use this algorithm because here only one loop is required and time complexity is less O(n)
int cs=0;
int ms=Integer.MIN_VALUE;
for(int i=0;i<numbers.length;i++){
cs+=numbers[i];
if(cs<0){
cs=0;
}
ms=Math.max(cs, ms);
}
System.out.println("the max subarray is: "+ms);
}
public static void main(String[] args) {
int numbers[] = { -2, -3,4,-1, -2, 1,5, -3 };
kadanes(numbers);
kadanesalgo(numbers);
}
}