給定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);
}
}