-
Notifications
You must be signed in to change notification settings - Fork 0
/
test2.java
43 lines (39 loc) · 952 Bytes
/
test2.java
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
/**
*第二题
*计算一个数组中子数组之和的最大值
*
*/
public class Test2 {
static int[] arr = {5,-3,2,4};// 需要求的数组
static int maxIndex = arr.length - 1;// 数组的最大下标
public static void main(String[] args) {
findMaxArr2();
System.out.println("\n-------------");
}
// 2.二层for循环求解
static void findMaxArr2() {
int max = arr[0];// 最大值
int sum;// 求和
int startIndex = 0;
int endIndex = 0;
for (int i = 0; i <= maxIndex; i++) {
sum = 0;
for (int j = i; j <= maxIndex; j++) {
sum += arr[j];
if (sum > max) {
max = sum;
startIndex = i;
endIndex = j;
}
}
}
System.out.println("最大值为:" + max);
printArr(startIndex, endIndex);
}
// 根据下标开始结束值,打印数组
static void printArr(int startIndex, int endIndex) {
for (int i = startIndex; i <= endIndex; i++) {
System.out.print(arr[i] + " ");
}
}
}