-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSolution.java
More file actions
40 lines (36 loc) · 1.32 KB
/
Solution.java
File metadata and controls
40 lines (36 loc) · 1.32 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
package dp.maxsubarray;
import java.util.Scanner;
public class Solution {
public static void main(String args[] ) throws Exception {
Scanner scanner = new Scanner(System.in);
for (int t = scanner.nextInt(); t > 0; --t) {
int n = scanner.nextInt();
int[] array = new int[n];
for (int i = 0; i < n; ++i)
array[i] = scanner.nextInt();
MaxSubArray maxSubArray = new MaxSubArray(array);
System.out.print(maxSubArray.contiguousMax);
System.out.print(' ');
System.out.print(maxSubArray.nonContiguousMax);
System.out.println();
}
}
}
class MaxSubArray {
int contiguousMax;
int nonContiguousMax;
MaxSubArray(int[] array) {
int nextPosMax = contiguousMax = nonContiguousMax = array[array.length - 1];
for (int i = array.length - 2; i >= 0; --i) {
int current = array[i];
int currentMax = Math.max(current, current + nextPosMax);
if (currentMax > contiguousMax)
contiguousMax = currentMax;
if (nonContiguousMax >= 0 && current > 0)
nonContiguousMax += current;
else if (current > nonContiguousMax)
nonContiguousMax = current;
nextPosMax = currentMax;
}
}
}