MaxSum100K

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

public class MaxSum100K {

static int posum = 0;
static int preps = 0;
static int nesum = 0;
static int hpos = 0;
static int prehp = 0;
static int tpos = 0;
static int pretp = 0;
static int curp = 0;

// static int allsum = 0;

public static void main(String[] args) throws IOException {
    // TODO
    WriterFile();
    @SuppressWarnings("resource")
    Scanner sc = new Scanner(new File("src/file/100000"));
    int tmp;
    boolean hasP = false;
    while (sc.hasNext()) {
        tpos++;
        tmp = sc.nextInt();
        // allsum += tmp;
        if (tmp >= 0) {
            if (!hasP) {
                hpos = tpos;
                hasP = true;
            }
            posum += tmp;
        } else if (hasP) {
            curp = tpos - 1;
            nesum += tmp;
            while (sc.hasNext()) {
                tpos++;
                tmp = sc.nextInt();
                // allsum += tmp;
                if (tmp >= 0) {
                    if (posum > preps) {
                        preps = posum;
                        prehp = hpos;
                        pretp = curp;
                    }
                    posum += nesum;
                    nesum = 0;
                    if (posum > 0)
                        posum += tmp;
                    else {
                        posum = tmp;
                        hpos = tpos;
                    }
                    break;
                } else {
                    nesum += tmp;
                }
            }
        }
    }
    if (posum > preps)
        System.out.println(posum + "--" + hpos + "--" + tpos);
    else
        System.out.println(preps + "--" + prehp + "--" + pretp);
    // System.out.println(allsum);
}

private static void WriterFile() throws IOException {
    // TODO Auto-generated method stub
    FileWriter fw = new FileWriter("src/file/100000");
    for (int i = 0; i < 2000; i++) {
        for (int j = 0; j < 50; j++)
            fw.write((int) (Math.random() * 2000 - 1000) + " ");
        fw.write("\n");
    }
    fw.close();
}

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章