Program Design ideas:
In order to divide the array, first determine the size of a single array of elements, the next two, ascending, and finally the results are compared to assign values, output the maximum results.
1 Packageketangtest;2 //Zhang Sheng-hui, Conge Jia 2017.3.203 Public classTest {4 Public Static voidMain (String args[]) {5 intb[]={-7,9,-2,84};6 inta[]={-7,9,-2,84,-7,9,-2,84};7 intmax,max2,max3,max4;8Max=a[0];9 intMax=max;//max values are judged with the maximum value each time, and then replacedTen for(inti=0;i<a.length;i++) One { A if(a[i]>max) - { -max=A[i]; the } -Max2=Max; - if(i<a.length-1)//handle out-of-bounds issues and judge over-bounds skipping - { + if(a[i]+a[i+1]>max2) - { +Max2=a[i]+a[i+1]; A } at } -max3=Max2; - if(max3>Max) - { -max=max3; - } in if(i<a.length-2) - { to if(a[i]+a[i+1]+a[i+2]>max3) + { -Max3=a[i]+a[i+1]+a[i+2]; the } * } $max4=max3;Panax Notoginseng if(max4>Max) - { themax=max4; + } A if(i<a.length-3) the { + if(a[i]+a[i+1]+a[i+2]+a[i+3]>max4) - { $Max4=a[i]+a[i+1]+a[i+2]+a[i+3]; $ } - } - if(max4>Max) the { -max=max4;Wuyi } the - } Wu System.out.println (Max); - } About $}
Program Run Result:
Program compilation error Results analysis:
Because it is necessary to use a for loop when judging an array, the result is that when judging the for loop of an element, it is possible to judge two or more, and then add the judging condition to limit it to solve the problem.
Finding the largest subarray in a Java array