这次是将数组的首尾相连,依然输出最大子数组的和,但是若最大子数组的长度大于原先的长度则不能输出。首尾相接形成循环,把这个循环展开形成一个一维数组,形成的一维数组就是将前n-1个数放在最后一个数后面,形成一个新数组,然后就可以直接用求一维数组最大子数组的方法来解决。
源代码:
package lianxi; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.math.BigInteger; import java.util.Scanner; public class App7 { public static void main(String[] args) throws IOException { Scanner in= new Scanner(System.in); //writeFile(); int hang=gethang(); String[] num=getnum(hang); String[] num2=new String [hang]; String max="0"; BigInteger bi,bi2; int s; boolean f=false; for(s=0;s<num.length;s++) { if(num[s]==null)break; bi=new BigInteger (num[s]); if(bi.max(BigInteger.valueOf(0))!=BigInteger.valueOf(0))f=true; } if(f==true) { max=num[0]; num2[0]=num[0]; for(int i=1;i<s;i++) { //num2[i]=num2[i-1]+num[i]; bi=new BigInteger (num[i]); bi2=new BigInteger (num2[i-1]); num2[i]=""+bi2.add(bi); if(bi.max(bi2)==bi)max=num2[i]; } for(int i=0,j=0;j<s;) { //循环减去第一个 bi=new BigInteger (num2[i]); bi2=new BigInteger (num[j]); bi=bi.subtract(bi2); if(bi.max(bi2)==bi)max=num2[i]; if(i==s-1) {j++;i=j;} else i++; } } else { max=num[0]; num2[0]=num[0]; for(int i=1;i<s;i++) { num2[i]=num2[i-1]+num[i]; bi=new BigInteger (num[i]); bi2=new BigInteger (num[i-1]); if(bi.max(bi2)==bi)max=num2[i]; } } System.out.println(max); //add(); in.close(); } public static int gethang() { int i=0; try (FileReader reader = new FileReader("text.txt"); BufferedReader br = new BufferedReader(reader)) { String line; while ((line = br.readLine()) != null) { i++; } } catch (IOException e) { e.printStackTrace(); } return i; } public static String[] getnum(int lang) throws IOException { String [] in=new String[lang]; int i=0; try (FileReader reader = new FileReader("text.txt"); BufferedReader br = new BufferedReader(reader)) { String line; while ((line = br.readLine()) != null) { in[i]= line; i++; } } catch (IOException e) { e.printStackTrace(); } return in; } public void writeFile() { int i=0; int fu=0; try { File writeName = new File("text.txt"); writeName.createNewFile(); try (FileWriter writer = new FileWriter(writeName); BufferedWriter out = new BufferedWriter(writer) ) { for(int j=0;j<150;j++) { i=1+(int)(Math.random()*9); //fu=1+(int)(Math.random()*2); //if(fu==1)i=0-i; out.write(i+" "); // 换行 out.flush(); } } } catch (IOException e) { e.printStackTrace(); } } public static void add() throws IOException { int i=0; try (FileReader reader = new FileReader("text.txt"); BufferedReader br = new BufferedReader(reader)) { String line; while ((line = br.readLine()) != null) { i+=Integer.parseInt(line); } } catch (IOException e) { e.printStackTrace(); } System.out.println("sum="+i); } }