Finding the largest subarray in a Java array

Source: Internet
Author: User

 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.