思路:
用max 记录最大值,用cur记录当前累加值
当cur > max 时,max 的值改为cur的值,当cur 小于0时
cur 赋值为0
代码实现:
public class Client { public static void main(String[] args) { int[] ints = {3,5,-2,6}; int cur = ints[0]; int max = ints[0]; for (int i = 1; i < ints.length; i++) { cur += ints[i]; if(cur > max){ max = cur; } if(cur < 0){ cur = 0; } } System.out.println("max:" + max); } }