package com.sum3; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.util.ArrayList; public class Sum { public static boolean isInt(String val) { try { Integer.parseInt(val); return true; } catch (NumberFormatException e) { return false; } } public static void main(String[] args) throws IOException { try { FileWriter fw = new FileWriter("Test.txt"); BufferedWriter bw = new BufferedWriter(fw); for (int i = 0; i < 100; i++) { java.util.Random rnd = new java.util.Random(); int n = rnd.nextInt(2000)-1000; String s = n + ""; bw.write(s); bw.newLine(); } bw.close(); fw.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } ArrayList<String> arrList = new ArrayList<>(); try { FileReader fr = new FileReader("Test.txt"); BufferedReader bf = new BufferedReader(fr); String st; while ((st = bf.readLine()) != null) { arrList.add(st); } bf.close(); fr.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } //长度 int len = arrList.size(); BigInteger a[] = new BigInteger[len]; BigInteger b[] = new BigInteger[20000000]; for (int i = 0; i < len; i++) { //数组转移 String s=arrList.get(i); a[i]=new BigInteger(String.valueOf(s)); } System.out.println(large(a, len)); // 打印最大子数组 } private static BigInteger large(BigInteger[] a, int len) { // TODO Auto-generated method stub BigInteger max = a[0]; BigInteger max2 =new BigInteger("0"); for (int i = 0; i < len; i++) { max2 = max2.add(a[i]).max(a[0]); // 几个连续最大的值 max = max.max (max2); // 目前为止最大值 } return max; } private static int max(int a, int b) { if (a > b) return a; else return b; } }
package com.sun3; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class Test { private static BufferedReader br; public static void main(String[] args) throws IOException { br = new BufferedReader(new FileReader("C:\Users\hp\Desktop\shuzu.txt")); String s=""; String s1; while((s1=br.readLine())!=null) { s=s+s1; } String [] data=s.split(" "); int [] datas=new int [data.length]; //将String类型数组转成int类型 for(int j=0;j<data.length;j++) { datas[j]=Integer.parseInt(data[j]); } for(int i=0;i<datas.length;i++) { System.out.print(datas[i]+" "); } double sum = 0; // max为子数组的最大和 double max = 0; for (int i=0,j = 0; j< datas.length; j++,i++) { sum=sum+datas[i];// 求和 if (sum < 0) {// 如果当前求得总和为负数的话,就将其清零,并且开始位置从下一个位置开始 sum = 0; } if (sum > max) {// 如果求得总和大于之前的最大值的话,就将sum赋值给max,同时记录最后的位置 max = sum; } } System.out.println("Max:" + max); } }
不太懂如何实现,没弄出来,还在继续努力中。