给定K个整数组成的序列{ N1 , N2 , …, NK},“连续子列”被定义为{ Ni , Ni+1 , …, Nj },其中 1≤i≤j≤K。“最大子列和”则被定义为所有连续子列元素的和中最大者。例如给定序列{ -2, 11, -4, 13, -5, -2 },其连续子列{ 11, -4, 13 }有最大的和20。现要求你编写程序,计算给定整数序列的最大子列和。
本题旨在测试各种不同的算法在各种数据情况下的表现。各组测试数据特点如下:
数据1:与样例等价,测试基本正确性;
数据2:102个随机整数;
数据3:103个随机整数;
数据4:104个随机整数;
数据5:105个随机整数;
输入格式:
输入第1行给出正整数K (≤100000);第2行给出K个整数,其间以空格分隔。
输出格式:
在一行中输出最大子列和。如果序列中所有整数皆为负数,则输出0。
输入样例:
6
-2 11 -4 13 -5 -2
输出样例:
20
java代码实现:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n,num,sum=0,max=0;
boolean flag = false;
n = sc.nextInt();
for (int i = 0; i < n; i++) {
num = sc.nextInt();
if (num>0) flag = true;
sum += num;
if (sum>=max) max = sum;
else if (sum<0) sum = 0;
}
if (flag) System.out.println(max);
else System.out.println("0");
}
}
优化:运行速度提高
BufferedReader从字符输入流读取文本,缓冲字符,以提供字符,数组和行的高效读取
为了最大的效率,请考虑在BufferedReader中包装一个InputStreamReader。 例如:
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(sc.readLine());
String[] str = sc.readLine().split(" ");
boolean flag = false;
int thissum=0,maxsum=0;
for (int i = 0; i < n; i++) {
int num = Integer.parseInt(str[i]);
if (num>0) flag = true;
thissum+=num;
if (thissum>maxsum) maxsum = thissum;
else if (thissum<0) thissum = 0;
}
if (flag) System.out.println(maxsum);
else System.out.println(0);
}
}
Maximum Subsequence Sum
输入样例:
10
-10 1 2 3 4 -5 -23 3 7 -21
输出样例:
10 1 4
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader sc = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(sc.readLine());
String[] str = sc.readLine().split(" ");
int[] nums = new int[n];
int count = 0;
for (int i = 0; i < str.length; i++) {
nums[i] = Integer.parseInt(str[i]);
if (nums[i]<0) count++;
}
if (count==n) {
System.out.println(0+" "+nums[0]+" "+nums[n-1]);
return;
}
int thissum=0,maxsum=-1;
int first=0,last=0,temp=0;
for (int i = 0; i < nums.length; i++) {
thissum += nums[i];
if (thissum>maxsum) {
maxsum = thissum;
first = nums[temp];
last = nums[i];
}
else if (thissum < 0) {
thissum = 0;
temp=i+1;
}
}
System.out.println(maxsum+" "+first+" "+last);
}
}