package com.supermars.practice;
import java.io.BufferedInputStream;
import java.util.Scanner;
public class 最大连续和1 {
/*
* 暴力枚举
*/
static Scanner cin = new Scanner(new BufferedInputStream(System.in));
static int A[] = new int[1 << 7];
public static void main(String[] args) {
while (cin.hasNext()) {
int n = cin.nextInt();
for (int i = 0; i < n; i++) {
A[i]=cin.nextInt();
}
int best=A[0];
for (int i = 0; i < n; i++) {
for (int j = i; j <n; j++) {
int sum=0;
for (int k = i; k <=j; k++) {
sum+=A[k];
}
best=best<sum?sum:best;
}
}
System.out.println(best);
}
}
}
————————————–
package com.supermars.practice;
import java.io.BufferedInputStream;
import java.util.Scanner;
public class 最大连续和2 {
/**
* S[i]=A1+A2..+Ai Ai+..Aj=S[j]-S[i-1]
*/
static Scanner cin = new Scanner(new BufferedInputStream(System.in));
static int A[] = new int[1 << 7];
static int S[] = new int[1 << 7];
public static void main(String[] args) {
while (cin.hasNext()) {
int n = cin.nextInt();
for (int i = 1; i <= n; i++) {
A[i] = cin.nextInt();
}
// 求前缀S
for (int i = 1; i <= n; i++) {
S[i] += S[i - 1] + A[i];
}
// S[j]-S[i-1] 最大
int best = 0;
for (int i = 1; i <= n; i++) {
int sum = 0;
for (int j = i; j <= n; j++) {
best = best < (sum = (S[j] - S[i - 1])) ? sum : best;
}
}
System.out.println(best);
}
}
}
—————————–
package com.supermars.practice;
import java.io.BufferedInputStream;
import java.util.Scanner;
public class 最大连续和3 {
static Scanner cin = new Scanner(new BufferedInputStream(System.in));
static int A[] = new int[1 << 7];
public static void main(String[] args) {
while (cin.hasNext()) {
int n = cin.nextInt();
for (int i = 0; i < n; i++) {
A[i] = cin.nextInt();
}
System.out.println(maxsum(A, 0, n));
}
}
private static int maxsum(int[] A, int x, int y) {
int m = 0, max = 0, l, r;
if (y - x == 1)
return A[x]; // 只有一个元素时返回
m = x + (y - x) / 2;// 划分[x,m)[m,y)
l = maxsum(A, x, m);
r = maxsum(A, m, y);
max = l > r ? l : r;
// 3合并(1)
int v = 0, L = A[m - 1];
for (int i = m - 1; i >= x; i--) {
L = L < (v += A[i]) ? v : L;
}
int R = A[m];
v = 0;
// 3合并(2)
for (int i = m; i < y; i++) {
R = R < (v += A[i]) ? v : R;
}
return max > (L + R) ? max : (L + R);
}
}