forked from destiny1020/algorithm_playground
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSubOneDim.java
More file actions
57 lines (41 loc) · 942 Bytes
/
MaxSubOneDim.java
File metadata and controls
57 lines (41 loc) · 942 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
51
52
53
54
55
56
57
package misc;
import org.junit.Test;
public class MaxSubOneDim {
public static int[] getMaxSub(int[] arr) {
int previous = arr[0];
int current;
int lastFrom = 0;
int from = 0;
int to = 0;
int max= previous;
for(int i = 1; i < arr.length; i++) {
int possible = previous + arr[i];
if(possible > arr[i]) {
current = possible;
} else {
lastFrom = i;
current = arr[i];
}
if(current > max) {
max = current;
to = i;
from = lastFrom;
}
previous = current;
}
int[] res = new int[3];
res[0] = max;
res[1] = from;
res[2] = to;
return res;
}
@Test
public void testMaxSub() {
// int[] test = {-1, 3, 4, -4, 5, -9, 5};
int[] test = {1, -9, 2, -8, 4};
int[] results = MaxSubOneDim.getMaxSub(test);
System.out.println("Result: " + results[0]);
System.out.println("From: " + results[1]);
System.out.println("To: " + results[2]);
}
}