参考了一篇学长的博客,受益匪浅,
通过不断累加,当和变成负数归零从一个数开始加,之前的结果保存到max,每一次的结果都跟max对比,保证只要不低于0的负数都可以加进来
1 public class text { 2 public static void main(String[] args) { 3 4 System.out.print("输入数组长度:" ); 5 Scanner cin = new Scanner(System.in); 6 int[] list = new int[1000000]; 7 int n = cin.nextInt(); 8 for (int i = 0; i < n; i++) { 9 list[i] = cin.nextInt(); 10 } 11 12 int max = list[0]; 13 int result = 0; 14 15 for (int j = 0; j < n; j++) 16 { 17 result = result + list[j]; 18 if(result > max) 19 { 20 max = result; 21 } 22 else if ( result < 0) 23 { 24 result = 0; 25 } 26 } 27 System.out.print("最大子数组:" ); 28 System.out.print(max); 29 } 30 }
标签:课堂练习,int,max,list,System,result,数组,out,最大 From: https://www.cnblogs.com/fan-wang/p/17185391.html