Microsoft algorithm 100 question 03 to find the largest and the sub-array

Source: Internet
Author: User

3. Find the maximum and large array of sub-arrays
Topic:
Enter an array of shapes with positive and negative numbers in the array.
One or more consecutive integers in an array make up a sub-array, each of which has a and.
The maximum value for the and of all sub-arrays. Requires a time complexity of O (n).
For example, the input array is 1,-2, 3, 10,-4, 7, 2,-5, and the largest subarray is 3, 10,-4, 7, 2,
So the output is the and 18 of the subarray.

Idea: Use the auxiliary variable Max to record the maximum sum of the subarray, and to begin the traversal from the array header, if the array element is a negative number with the sum of the previous sum, reset the sum result to zero, otherwise the resulting sum value will be compared to max if it is less than Max, and the next element of the array continues to be evaluated

1  PackageCom.rui.microsoft;2 3  Public classTest03_maxsubarray {4 5      Public Static voidMain (string[] args) {6         int[] Array = {1,-2, 3, 10,-4, 7, 2,-5};7 System.out.println (Findmax (array));8     }9     Ten     Private Static intFindmax (int[] Array) { One         intres = 0; A         intMax =Res; -          -          for(inti = 0; i < Array.Length; i++){ theRes + =Array[i]; -             if(Res >max) { -Max =Res; -}Else if(Res < 0){ +res = 0; -                 Continue; +             } A              at         } -          -         returnMax; -     } -}

Microsoft algorithm 100 question 03 to find the largest and the sub-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.