"Sword refers to offer study" "Face question 31: The maximum and" of continuous sub-arrays

Source: Internet
Author: User

Title: Enter an array of integers with positive and negative numbers in the array. One or more consecutive integers in an array make up a sub-array. The maximum value for the and of all sub-arrays. Requires a time complexity of O (n). Example Description:

For example, the input array is {1,-2, 3, 10,-4, 7, 2,-5}, and the largest sub-array is {3, 10,-4, 7, 2}. So the output is the and 18 of the subarray.

Problem Solving Ideas:

Solution One: Example analysis of the law of the array.

We try to accumulate each number in the sample array from beginning to end. Initialized and is 0. The first step plus the first number 1, at this time and 1. The next step is to add the number 2, and it becomes-1. The third step is to brush the number 3. We note that the sum of the previous cumulative and 1, less than 0, if used-1 plus 3, the sum is 2, is smaller than the 3 itself. That is, the sub-array starting with the first number and the sum of the sub-arrays that begin with the third number. So we don't have to think about the sub-arrays that start with the first number, and the accumulated sum is discarded.

We start with the third number again, and we get 3 at this point. Next fourth step plus 10, get and 13. The fifth step Plus-4, and 9. We found that since 4 is a negative number, the sum of 4 is then less than the original and smaller. So we're going to save what we got before and 13, and it's probably the largest of the sub-arrays. The sixth step plus the number. The result of 7,9 plus 7 is 16, at this time and greater than the previous largest and 13, the largest sub-array and updated from 13 to 16. The seventh step plus 2, add the sum of 18, and we also want to update the sum of the largest sub-array. The eighth step plus the last number-5, because the resulting and is 13, less than the previous largest and 18, so the final largest subarray of the and 18, corresponding sub-array is {3, 10,-4, 7, 2}.

Solution Two: Apply dynamic attribution method.

You can use the idea of dynamic programming to analyze this problem. If you use the function f (i) to denote the maximum and the number of sub-arrays ending in the first digit, then we need to find max[f (i)], where 0 <= i < N. We can use the following formula to find F (i):

The meaning of this formula: when all the numbers in the sub-array ending with the i-1 number are less than 0 o'clock, if the number of the negative number is added to the first number, the result is smaller than the first digit, so the sub-array ending with the number I in this case is the first number itself. If the sum of all the numbers in the subarray ending in the i-1 number is greater than 0, the sum of all the numbers in the sub-array ending with the I-number is obtained with the number of the I numbers.

The first implementation of the subject

Code implementation:
 Public  class Test31 {    /** * Title 2 Enter an array of integers with positive and negative numbers in the array. One or more of the integers in the array make up a sub-array. The maximum value for the and of all sub-arrays.     Requires a time complexity of O (n). * * @param arr input array * @return largest contiguous subarray and */     Public Static int Findgreatestsumofsubarray(int[] arr) {//Parameter check        if(arr = =NULL|| Arr.length <1) {Throw NewIllegalArgumentException ("Array must contain an element"); }//Record the largest sub-array and, at the beginning, is the smallest integer        intmax = Integer.min_value;//Current and        intCurmax =0;//Array traversal         for(intI:arr) {//If current and less than equals 0, reset current and            if(Curmax <=0) {Curmax = i; }//If current and greater than 0, accumulate current and            Else{Curmax + = i; }//update record to the most in sub-array and            if(Max < Curmax)            {max = Curmax; }        }returnMax } Public Static void Main(string[] args) {int[] data = {1, -2,3,Ten, -4,7,2, -5};int[] data2 = {-2, -8, -1, -5, -9};int[] Data3 = {2,8,1,5,9};        System.out.println (Findgreatestsumofsubarray (data));        System.out.println (Findgreatestsumofsubarray (data2));    System.out.println (Findgreatestsumofsubarray (data3)); }}
Operation Result:

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

"Sword refers to offer learning" "Face question 31: maximum and" of contiguous Subarray "

Related Article

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.