最大子段和 java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main{
	public static void main(String args[]) throws NumberFormatException, IOException {
		 BufferedReader bf=new BufferedReader(new InputStreamReader(System.in) );
	    int n=Integer.parseInt(bf.readLine());
	    long tmax=0,maxn=0,temp;
	    tmax=Long.parseLong(bf.readLine());
	   
	    for(int i=1;i<n;++i)
	    {temp=Long.parseLong(bf.readLine());
	    	if(tmax<0) {
	    		tmax=temp;
	    	}
	    	else tmax+=temp;
	    	if(maxn<tmax)
	    		maxn=tmax;
	    }
	    System.out.println(maxn);
	}
}




N个整数组成的序列a[1],a[2],a[3],…,a[n], 求该序列如a[i]+a[i+1]+…+a[j]的连续子段和的最大值。当所给的整数均为负数时和为0。
例如:-2,11,-4,13,-5,-2,和最大的子段为:11,-4,13。和为20。
Input
第1行:整数序列的长度N(2 <= N <= 50000)
第2 - N + 1行:N个整数(-10^9 <= A[i] <= 10^9)
Output
输出最大子段和。
Input示例
6
-2
11
-4
13
-5
-2
Output示例
20

猜你喜欢

转载自blog.csdn.net/qq_37437892/article/details/80380911