public class Zhejiang { public static void main(String[] args) { int[] arr=new int[] {1,-2,3,10,-4,7,2,-5}; int i=getGreatestSum(arr); System.out.println(i); } private static int getGreatestSum(int[] arr) { if (arr==null||arr.length==0) { return 0; } int greatestSum=0; int temp=greatestSum; for (int i = 0; i < arr.length; i++) { temp+=arr[i]; if (temp<0) {//如果当前和已经为负数了,直接抛弃这个值,应该数组元素中一定有正数,选择任何一个整数都要大于负数 temp=0; } if(temp>greatestSum) {//发现新的最大和,将其重新赋给greatestSum greatestSum=temp; } } if (greatestSum==0) {//因为很多值被抛弃了,会发生这种极端情况,所以最后将单个元素中的最大值赋给greatestSum greatestSum=arr[0]; for (int i = 1; i < arr.length; i++) { if (greatestSum<arr[i]) { greatestSum=arr[i]; } } } return greatestSum; } }