[Sword refers to Offer learning] [interview question 31: the largest sum of consecutive sub-arrays], sword refers to offer

Source: Internet
Author: User

[Sword refers to Offer learning] [interview question 31: the largest sum of consecutive sub-arrays], sword refers to offer
Question: enter an integer array with a positive or negative number in the array. One or more consecutive integers in the array form a sub-array. Returns the maximum value of the sum of all sub-arrays. The time complexity is O (n ). Example:

For example, the input array is {1,-2, 3, 10,-4, 7, 2,-5}, and the maximum sub-array is {3, 10,-4, 7, 2 }. Therefore, the output is the sum of 18 of the sub-array.

Solution:

Solution 1: give an example to analyze the rule of arrays.

We try to accumulate each number in the example array from start to end. The initialization value is 0. The first step is to add the first number 1, which is 1. The next step is to add the number-2, and the sum is changed to-1. Step 3: refresh the number 3. We noticed that since the sum accumulated previously is-1 and less than 0, if we add 3 with-1, the sum obtained is 2, which is smaller than 3. That is to say, the Child array starting from the first digit and the sum of the Child array starting from the third digit are smaller. Therefore, we do not need to consider the sub-array starting with the first number, and the previous accumulated and also discarded.

We start accumulating from the third number again, and now we get the sum of 3. Add 10 in Step 4 to obtain the sum of 13. In step 5, add-4 and 9. We found that since-4 is a negative number, the sum obtained after-4 is smaller than the original sum. Therefore, we need to save the obtained sum 13, which may be the sum of the largest subarray. In step 6, the result of adding numbers. 7, 9, and 7 is 16. The sum is larger than the sum of the largest and 13, and the sum of the largest sub-array is updated from 13 to 16. Add 2 in Step 7, and the sum of the accumulated values is 18. At the same time, we also need to update the sum of the largest sub-array. In step 8, add the last number-5. Because the obtained sum is 13, which is smaller than the previous largest and 18, the final largest sub-array is 18, and the corresponding sub-array is {3, 10,-4, 7, 2 }.

Solution 2: Dynamic grouping of applications.

This problem can be analyzed using the idea of dynamic planning. If f (I) is used to represent the largest sum of the subarrays ending with the number I, we need to find max [f (I)], 0 <= I <n. We can calculate f (I) using the edge normalization formula below ):

The meaning of this formula: when the sum of all the numbers in the Child array ending with a number in the I-1 is less than 0, if this negative number is accumulated with the number of the I, the result is smaller than the number I. In this case, the subarray ending with the number I is the number I. If the sum of all numbers in the Child array ending with a number in the I-1 is greater than 0, accumulate with the number I to get the sum of all the numbers in the subarray ending with the number I.

This article uses the first implementation method

Code implementation:
Public class Test31 {/*** Question 2: enter an integer array, and the array contains both positive and negative numbers. One or more consecutive integers in the array form a sub-array. Returns the maximum value of the sum of all sub-arrays. The time complexity is O (n ). ** @ Param arr input array * @ return maximum continuous sub-array and */public static int findGreatestSumOfSubArray (int [] arr) {// parameter verification if (arr = null | arr. length <1) {throw new IllegalArgumentException ("Array must contain an element");} // records the largest sub-Array and the minimum Integer int max = Integer at the beginning. MIN_VALUE; // current and int curMax = 0; // array traversal for (int I: arr) {// if the current and less than or equal to 0, reset the current and if (curMax <= 0) {curMax = I;} // if the current and if greater than 0, accumulate the current and else {curMax + = I ;} // update the records to the most appropriate sub-array and if (max <curMax) {max = curMax ;}} return max ;}public static void main (String [] args) {int [] data = {1,-2, 3, 10,-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 ));}}
Running result:

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

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.