01-复杂度1. 最大子列和问题(20)

给定K个整数组成的序列{ N1, N2, ..., NK },“连续子列”被定义为{ Ni, Ni+1, ..., Nj },其中 1 <= i <= j <= K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。

输入格式:

输入第1行给出正整数 K (<= 100000);第2行给出K个整数,其间以空格分隔。

输出格式:

在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。

输入样例:
6
-2 11 -4 13 -5 -2
输出样例:
20


 
1
import java.io.BufferedReader; 2 import java.io.IOException; 3 import java.io.InputStreamReader; 4 5 public class Main 6 { 7 static private int K; 8 static private int[] list; 9 public static void main(String[] args) throws IOException 10 { 11 // System.out.println("..."); 12 BufferedReader buf=new BufferedReader(new InputStreamReader(System.in)); 13 String line=buf.readLine(); 14 K=Integer.parseInt(line); 15 list=new int[K]; 16 line=buf.readLine(); 17 String[] temp=line.split(" "); 18 for(int i=0;i<K;i++) 19 list[i]=Integer.parseInt(temp[i]); 20 // 判断是否都是0 21 boolean flag=false; 22 for(int i=0;i<K;i++) 23 { 24 if(list[i]>=0) 25 { 26 flag=true; 27 break; 28 } 29 } 30 if(flag==false) 31 { 32 System.out.print(0); 33 return; 34 } 35 36 int x=0; 37 int y=0; 38 for(int i=0;i<K;i++) 39 { 40 x=Math.max(x+list[i],0); 41 y=Math.max(y, x); 42 } 43 /* int sum=Integer.MIN_VALUE; 44 for(int i=0;i<K;i++) 45 { 46 for(int j=i;j<K;j++) 47 { 48 sum=Math.max(sum,cout(i,j)); 49 } 50 }*/ 51 System.out.print(y); 52 53 } 54 55 56 public static int cout(int i,int j) 57 { 58 int sum=0; 59 for(;i<=j;i++) 60 sum+=list[i]; 61 return sum; 62 } 63 64 }
原文地址:https://www.cnblogs.com/qq1029579233/p/4399278.html