-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxSubSum.java
More file actions
84 lines (71 loc) · 2.09 KB
/
Copy pathMaxSubSum.java
File metadata and controls
84 lines (71 loc) · 2.09 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package dp;
import org.junit.Test;
import java.util.HashMap;
/**
* @Author: wei1
* @Date: Create in 2018/12/10 13:31
* @Description: 最大子串是要找出由数组成的
* 一维数组中和最大的连续子序列。比如{5,-3,4,2}
* 的最大子串就是 {5,-3,4,2},它的和是8,达到
* 最大;而 {5,-6,4,2}的最大子串是{4,2},它的
* 和是6。
*/
public class MaxSubSum {
class ResultType {
int start;
int end;
public ResultType() {
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public int getEnd() {
return end;
}
public void setEnd(int end) {
this.end = end;
}
public ResultType(int start, int end) {
this.start = start;
this.end = end;
}
}
public int maxSubSum(int[] arr, HashMap<Integer, ResultType> map) {
int max = 0;
ResultType resultType = new ResultType();
int sum = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] >= 0) {
if (sum == 0) {
resultType.start = i;
}
sum += arr[i];
max = max > sum ? max : sum;
} else {
if (sum >= max) {
resultType.end = i - 1;
map.put(max, new ResultType(resultType.start, resultType.end));
}
sum = 0;
}
}
if (!map.containsKey(max)) {
map.put(max, new ResultType(resultType.start, arr.length - 1));
}
return max;
}
@Test
public void test() {
HashMap<Integer, ResultType> map = new HashMap<>();
int[] arr = {5, -6, 4, 2, 0, -1, 3, -5};
int result = maxSubSum(arr, map);
System.out.println(result);
ResultType resultType = map.get(result);
for (int i = resultType.start; i <= resultType.end; i++) {
System.out.print(arr[i] + " ");
}
}
}