洛谷P1115最大子段和
代码
import java.io.*;
import java.math.BigInteger;
import java.util.*;
public class Main {
private static int[][] direct={{0,1},{1,0},{-1,0},{0,-1}};
private static AWriter writer = new AWriter(System.out);
private static AReader reader = new AReader(System.in);
private static long n;
private static double INFINITY=Double.POSITIVE_INFINITY;
private static int a[];
public static void main(String[] args) throws IOException {
int n=reader.nextInt();
a=new int[n];
for(int i=0;i<n;i++)
a[i]=reader.nextInt();
int ans=0;
int maxAns=-0x3f3f3f;
for(int i=0;i<n;i++){
ans+=a[i];
if(ans>maxAns)
maxAns=ans;
if(ans<0){
ans=0;
}
}
writer.println(maxAns);
writer.close();
reader.close();
}
}
class AReader implements Closeable {
private BufferedReader reader;
private StringTokenizer tokenizer;
public AReader(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
tokenizer = new StringTokenizer("");
}
private String innerNextLine() {
try {
return reader.readLine();
} catch (IOException ex) {
return null;
}
}
public boolean hasNext() {
while (!tokenizer.hasMoreTokens()) {
String nextLine = innerNextLine();
if (nextLine == null) {
return false;
}
tokenizer = new StringTokenizer(nextLine);
}
return true;
}
public String nextLine() {
tokenizer = new StringTokenizer("");
return innerNextLine();
}
public String next() {
hasNext();
return tokenizer.nextToken();
}
public int nextInt() {
return Integer.valueOf(next());
}
public long nextLong() {
return Long.valueOf(next());
}
public double nextDouble() {
return Double.valueOf(next());
}
public BigInteger nextBigInteger() {
return new BigInteger(next());
}
@Override
public void close() throws IOException {
reader.close();
}
}
// Fast writer for ACM By Azure99
class AWriter implements Closeable {
private BufferedWriter writer;
public AWriter(OutputStream outputStream) {
writer = new BufferedWriter(new OutputStreamWriter(outputStream));
}
public void print(Object object) throws IOException {
writer.write(object.toString());
}
public void println(Object object) throws IOException {
writer.write(object.toString());
writer.write("\n");
}
@Override
public void close() throws IOException {
writer.close();
}
}
思路
超级经典的一道题,还有 o ( n log n ) o(n\log n) o(nlogn)的动态规划法。