nyoj 44 子串和

题目链接: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;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值