One: Design ideas
First define an empty array with the same length as the original array, then assign the first number of the original array to the first position of the empty array, and then use the loop to compare the number of the original array with the previous number of the empty array for negative numbers. By comparing the second array, we can get the largest subarray in the integer array and the time complexity is O (n).
Two: Source code
//returns the and of the largest sub-array in an integer array. //Letter 1405-1 class 20142966 Huang WeipengImportJava.util.Scanner; Public classShuzu { Public Static voidMain (string[] args) {//TODO Auto-generated method stubs inti,length; System.out.println ("Please enter the number of numbers to compare:"); Scanner in=NewScanner (system.in); //Define Array LengthLength=In.nextint (); intlist[]=New int[length]; System.out.println ("Please enter the number you want to compare:"); Scanner T=NewScanner (system.in); //defining the contents of an array for(i=0;i<length;i++) {List[i]=T.nextint (); } //to define an empty storage array intsize[]=New int[length]; //Add the numbers in the array to find the maximum valueSize[0]=list[0]; for(i=1;i<length;i++) { if(size[i-1]<0) {Size[i]=List[i]; } Else{Size[i]=list[i]+size[i-1]; } } //find the maximum value for(i=0;i<length-1;i++) { if(size[0]<size[i+1]) {size[0]=size[i+1]; } } //Maximum output valueSystem.out.println (size[0]); }}
Three: Program results
Returns the maximum number of sub-arrays in an integer array and