package greast_subarray; import java.util.Scanner; public class max { public static void main(String[] args) { // TODO Auto-generated method stub int size; Scanner in=new Scanner(System.in); size=in.nextInt(); int a[]=new int[size]; for(int i=0;i<size;i++){ a[i]=in.nextInt(); } System.out.println(FindGreatestSumOfSubarray(a)); } public static int FindGreatestSumOfSubarray(int[] a){ int sum=a[0]; int temp=0; int end=0; int len=a.length; for(int i=0;i<len;i++){ temp+=a[i]; if(temp>sum){sum=temp;end=i;} if(temp<0){temp=a[i];} } temp=0; int sum1=0; for(int i=len-1;i>end;i--){ temp+=a[i]; if(temp>sum1){sum1=temp;} } return sum+sum1; } }
验证: