-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathResult.java
More file actions
52 lines (41 loc) · 1.34 KB
/
Result.java
File metadata and controls
52 lines (41 loc) · 1.34 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
42
43
44
45
46
47
48
49
50
51
52
package hackrank.algorithm.dynamic.maxsub;
import java.util.Arrays;
import java.util.List;
/**
* @see <a href="https://www.hackerrank.com/challenges/maxsubarray">The Maximum Subarray</a>
*/
public class Result {
/**
* @param arr List of integers; Constraint: list size = 1 to 100,000
* @return List with two integers: the maximum subarray and subsequence sums
*/
public static List<Integer> maxSubarray(List<Integer> arr) {
return Arrays.asList(findMaxSumContiguous(arr), findMaxSumNonContiguous(arr));
}
private static int findMaxSumContiguous(List<Integer> sequence) {
int bestSum = Integer.MIN_VALUE;
int currentSum = 0;
for (int value : sequence) {
currentSum += value;
if (currentSum >= bestSum) {
bestSum = currentSum;
}
if (currentSum < 0) {
currentSum = 0;
}
}
return bestSum;
}
private static int findMaxSumNonContiguous(List<Integer> sequence) {
int minNegative = Integer.MIN_VALUE;
int sum = 0;
for (int value : sequence) {
if (value > 0) {
sum += value;
} else if (value > minNegative) {
minNegative = value;
}
}
return sum > 0 ? sum : minNegative;
}
}