-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSubarrayPlus.java
More file actions
50 lines (36 loc) · 957 Bytes
/
Copy pathMaxSubarrayPlus.java
File metadata and controls
50 lines (36 loc) · 957 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import java.util.Scanner;
public class MaxSubarrayPlus {
public int maxContiguous = 0;
public int maxPositive = 0;
public void maxSubArray(int[] A) {
int newsum = A[0];
maxContiguous = A[0];
maxPositive = A[0];
for (int i = 1; i < A.length; i++) {
newsum = Math.max(newsum + A[i], A[i]);
maxContiguous = Math.max(maxContiguous, newsum);
if (maxPositive < 0) {
if (A[i] > maxPositive) {
maxPositive = A[i];
}
} else if (A[i] > 0) {
maxPositive += A[i];
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
MaxSubarrayPlus work = new MaxSubarrayPlus();
int cases = in.nextInt();
for (int i = 0; i < cases; i++) {
int size = in.nextInt();
int[] data = new int[size];
for (int j = 0; j < size; j++) {
data[j] = in.nextInt();
}
work.maxSubArray(data);
System.out.println(work.maxContiguous + " " + work.maxPositive);
}
in.close();
}
}