-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximumSubarray.java
More file actions
41 lines (38 loc) · 1.07 KB
/
MaximumSubarray.java
File metadata and controls
41 lines (38 loc) · 1.07 KB
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
public class MaximumSubarray {
public static int maxSum(int a[], int n) {
int sum = a[0], best = a[0], tmpS = 0, tmpE = 0, s=0,e=0;
for(int i=1;i<n;i++) {
if(sum < a[i]) {
sum = a[i];
tmpS = i;
tmpE = i;
}
else {
sum = sum + a[i];
tmpE = i;
}
if(best < sum) {
best = sum;
e = tmpE;
s = tmpS;
}
//System.out.println(sum + " " + e + " " + s);
}
return best;
}
public static int minSum(int a[], int n) {
int sum = a[0], best = a[0];
for(int i=1;i<n;i++) {
sum = Math.min(sum+a[i], a[i]);
best = Math.min(best, sum);
}
return best;
}
public static void main(String args[]) {
int a[] = {9,-4,-7,9};
int max1 = maxSum(a,a.length);
//if(max1 < 0)
System.out.println(maxSum(a,a.length));
System.out.println(minSum(a,a.length));
}
}