题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=44
这个题做过好久了,但是一直没有记录下来。。。好吧,开始!
题目大意:给一个整形数组,求连续非空子数组的最大和。
解题思路:这题,最重要的就是一个思路,用一个max变量始终记录连续最大子数组和,sum记录当前和,而sum的处理是最重要的!
上码更清楚!
import java.io.BufferedInputStream;
public class Main{
static BufferedInputStream bis = new BufferedInputStream(System.in);
public static void main(String[] args) throws Exception {
int n, sum, max, nCase;
nCase = getInt();// 对输入整数的优化
while (nCase-- != 0) {
n = getInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = getInt();
}
max = sum = arr[0];
for (int i = 1; i < n; i++) {
if (sum < 0) {//逻辑处理
sum = arr[i];
} else {
sum += arr[i];
}
max = Math.max(max, sum);//!!max始终记录最大的子序列和
}
System.out.println(max);
}
bis.close();
}
// 用BufferedInputStream的read()方法来减少读入的时间
static int getInt() throws Exception {
int i;
// ' ':32 '\t':9 '\n':10 '-':45 '0':48
// 除去间隔符
while ((i = bis.read()) < 45)
;
int temp = 0, mark = 1;
if (i == 45) {//读入的是负号
mark = -1;
i = bis.read();
}
while (i > 47) {
temp = temp * 10 + i - 48;
i = bis.read();
}
return mark * temp;
}
}
772

被折叠的 条评论
为什么被折叠?



