【问题描述】
求数组中最大连续子序列之和,如所有子序列之和都是负数则返回0。例如:
数组A:{-2,11,-4,13,-5,-2},则最大连续子序列之和为20,即11+(-4+13)= 20。
数组B:{1,3,-2,4,-5},则最大连续子序列之和为6,即1+3+(-2)+4= 6。
数组C:{-1,-2,-3,-5,-4},则最大连续子序列之和为0。
要求算法的时间复杂度为O(n)
【输入格式】
第一行是数组大小t(0 <= t <= 20)。第二行是t个数组元素。
【输出格式】
输出一个整数,表示最大连续子序列之和。
【样例输入】
6
-2 11 -4 13 -5 -2
【样例输出】
20
public class ch01 {
public void operate(int totalPerson,int[] numbs){
int i,j;
int max =numbs[0];
int[] temps=new int[totalPerson];
for(i=0;i
public class ch02 {
public int operate(int[] numbs){
int m=numbs[0];
int temp=0;
for (int numb : numbs) {
temp = Math.max(temp + numb, numb); //比较当前的值大还是累加之前的值大
m = Math.max(m, temp); //更新最大值
}
if(m<0){
m=0;
}
System.out.println("最大的连续子序列之和是(方法二):");
return m;
}
}
public class Test {
public static void main(String[] args) throws IOException {
String inputStr;
boolean mark=false;
int a=0;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
do {
try {
System.out.println("请输入数组的大小:");
inputStr = in.readLine();
a = Integer.parseInt(inputStr);
if (a <= 0) {
throw new NegativeIntegerException();
}
mark=true;
} catch (NumberFormatException | NegativeIntegerException e) {
System.out.println("非法输入!!!请输入一个正整数!");
}
}while(!mark);
mark=false;
int[] numbs = new int[a];
do {
try {
System.out.println("请依次输入数组的元素,敲回车隔开:");
for (int i=0;i



