Programmer interview essence 02

Source: Internet
Author: User

The maximum sum of sub-Arrays


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. Each sub-array has a sum.

Returns the maximum value of the sum of all sub-arrays. The time complexity is O (n ).


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 sum of 18 of the Child array.

=========================1,-2, 3, 10,-4, 7,2,-5, and the largest sub-array is 3, 10,-4, 7, 2 ============================


I. Question Analysis


Regardless of the algorithm, we should first analyze this problem from the most common way of thinking. A string of integer arrays has positive and negative values. How can we select the largest and largest subarrays?

1. The substring array must start with a positive number;

2. It must end with a positive number as the last element.


Why? For example: 1,-2, 3, 10,-4, 7, 2,-5. If a sub-array starts with a negative number, the sub-array must be smaller than the sub-array starting with a positive number in the sub-array... Is it dizzy?

Here we use the reverse verification method to prove it ~


Assume that the maximum sub-array of an array starts with A negative number, that is, A = {-2, 3, 10,-4, 7, 2} is the largest sub-array, then the sum of the sub-array B of A = {3, 10,-4, 7, 2} must be greater than that of. Because A =-2 + B;

B> A. Assume that A is the largest sub-array. Obviously, the conclusion is in conflict with our assumptions (B is bigger ~). From this we know that the sub-array must start with a positive number. Similarly, we can conclude that this sub-array must end with a positive number as the last element.


So what do we learn from this conclusion? It's hard to find all the sub-arrays starting with a positive number and comparing their sums? Of course, yes, but the O (n) question cannot meet the requirements. Why? Let's take a look at this example: 1,-2, 3, 10,-4, 7, 2,-5.

First, we traverse from the beginning: First we find the first positive number, that is, 1.

==== 1,-2, 3

==== 1,-2, 3, 10

==== 1,-2, 3, 10,-4, 7

==== 1,-2, 3, 10,-4, 7, 2

This is the first time. A total of n numbers are compared,

The second time, we continue to look forward for the Child array starting with a positive number and ending with a positive number... and so on. You will find that in the worst case, n * (n-1) *... * 1 is n! (The original array is a positive number ). The most optimistic case is {1,-1,-1 ,..., -1} in this case, you only need to traverse it once, but the premise is that you have to have a record mark to tell you that there are n numbers and (n-1) negative numbers. Obviously, this is only an ideal situation. We should analyze the problem based on the general situation. In algorithm design analysis, the nickname is: Average time complexity ~


So here we will introduce something called "greedy algorithm. So if you want to expand your knowledge, you can learn about greedy algorithms. Why should we use greedy algorithms to solve this problem? Because many problems that can be solved by greedy algorithms have two important properties:Greedy choiceAndOptimal sub-structure.

Wipe ~ What do you mean?

1. Greedy choice

The so-called Greedy choiceIt refers to the question Overall Optimal SolutionYou can use a series Local optimumIn other words, when considering the selection, we only consider the best choice for the current problem rather than the results of the sub-problem. This is the first basic element for the feasibility of greedy algorithms. Greedy algorithms make successive greedy choices in iterative ways. Each greedy choice simplifies the problem as a subproblem of smaller size. For a specific problem, to determine whether it has the greedy choice nature, it must prove that the greedy choice made by each step ultimately leads to the overall optimal solution of the problem.

2. Optimal sub-structure

When the optimal solution of a problem includes the optimal solution of its subproblems Optimal sub-structure. The optimal sub-structure of a problem is the key feature of the problem that can be solved by greedy algorithms.

The basic idea of greedy algorithms is as follows:

1. Create a mathematical model to describe the problem.

2. Divide the problem to several subproblems.

3. solve each subproblem and obtain the local optimal solution of the subproblem.

4. Merge the local optimal solution of the subproblem into a solution of the original solution.


So, based on the above introduction, we want to find and the largest sub-array, then we can find this sub-array from the beginning. We start from the first number (1,-2, 3, 10,-4, 7, 2,-5). At this time, we need to add the child array and sum to start to 0, in addition, we can ensure that the final sub-array must be greater than 0 (because there is positive and negative in this array, the final sub-array is a number, and it is the maximum positive in the entire array ). Therefore, when the sum of the current sum is less than 0, it is immediately discarded. Based on greedy selectivity, we think that if the preceding sum is smaller than 0, we should skip it and start again. Think about whether the proof here is the same as the proof that must begin with a positive number, so the proof above officially shows a greedy and selective performance. If the preceding sum is greater than 0 and the number of newly added values is greater than 0, the new group is the optimal solution after the update !!

If there is still a bit of confusion, let's continue to understand it in the Code ~

The procedure is as follows:

Int max_sub_array (int arr [], int size) {int I = 0; // a cursor that records the original array int sum = 0; // sum is used to record the sum of the first k numbers (k <n) int max =-(1 <30); // max records the largest sum we have found, at first we set it to-2 ^ 31 // loop to the size position. We can find the sub-array of the sub-array, that is, Suppose {1,-2, 3, 10,-4, 7, 2} // when we set size = 4, the actually tested array is {1,-2, 3, 10 }. While (I <size) {// This Is What we mentioned above. sum is always added to arr [I]. When sum <0, we discard sum, the number of the first k is skipped. because the number of the first k is not the optimal sub-structure, we set sum to 0 and start from the new one. Sum + = arr [I ++]; if (sum <0) {sum = 0 ;}// when sum is added with a positive number (sum new)> (original sum), while max is (original sum ). So we updated max. // When sum is added with a negative number (sum new) <(sum original), max is not updated. This is why the last number // must be greater than 0 else if (sum> max) {max = sum ;}} return max ;}

The test function is as follows:

int main(){int arr[] = {-1,3,5,-2, 7, 10, 3, -1};int a = 0;int b = 0;a = max_sub_array(arr, 5);b = max_sub_array(arr, 8);printf( "%d\n", a );printf( "%d\n", b );return 0;}


The test results are as follows:


Try it on your own ~


2. Is that all?


Is that all done? Yes. The question is over ~ But we can think more!

Excuse me, we found the largest and max, but where is this sub-array? Where does the child array of A = {1,-2, 3, 10,-4, 7, 2,-5} start from? Where is her starting position.


To solve this problem, we still follow the code to see what it has done.

Int max_starter (int arr [], int count) {// no difference between the three and the previous three: int I = 0; int max =-(1 <30 ); int sum = 0; // What do these two mean? // Starter_final: the starting position of the largest sub-group. What about starter? // This starter records the temporary starting value, which is quite awkward. Do you want to take a look at the example? For int arr [] = {-1, 3, 5,-12, 7, 10, 3,-1} // The first starter is 2, that is, arr [1] = 3, because (arr [0] =-1) <0, sum <0, Jump directly to arr [1] and start from again, so // Let's see What starter has? Arr = 3, arr = 7 here, right? Calculate by yourself. That is to say, starter records all possible start locations, and this starter_final records the starting position of the existing and largest subarrays through comparison. Int starter = 0; int starter_final = 0; while (I <count) {sum + = arr [I ++]; if (sum <0) {starter = I; sum = 0;} else if (sum> max) {max = sum; starter_final = starter ;}// we return the location. We need to add 1, that is, the position of arr [4] = 7 is 5th bits of the array. Return (starter_final + 1 );}

The test results are as follows:


Try it on your own ~


3. More, I need more power)


Yes, we can do more!

Now we know the largest subarray and the starting position of the original array. So what about this group leader? Can we know that she is {3, 10,-4, 7, 2.


It's actually quite easy. We know the sum of the array and the starting position. Then, subtract the element at the starting position from the sum, that is, 18-3 = 15. At the same time, move the sign pointing to the starting position to the back, and use a count to record the number of elements in the subarray. This is also a mess, so it is still an example to talk about: Here max = 18, count = 0, right,

Max = max-3 = 15, count ++ (so count = 1)

Max = max-10 = 5, count ++ (count = 2)

Max = max-(-4) = 9, count ++ (count = 3)

Max = max-7 = 2, count ++ (count = 4)

Max = max-2 = 0, count ++ (count = 5)


At this point, count is calculated, and a total of five numbers are in this sub-array. Knowing the position of the sub-array in the original array and her length ~ Then you can determine what she looks like, right?

If I don't speak, just look at the code ~

// Sub-Group length int max_sub_array_length (int arr [], int count) {int max_value = 0; int starter = 0; int length = 0; max_value = max_sub_array (arr, count); starter = max_starter (arr, count)-1; while (max_value> 0) {max_value-= arr [starter ++]; ++ length;} return length ;}

As for how to print it out, I will give it to you. Please try it !!!

Finally, list all the sample code:

/*************************************** ************: Zhong lingxiao * Time: 2014.1.6 * Subject: ********************************* * ****************/# include
 
  
# Include
  
   
// ******************* The largest subarray and ************** * *********** int max_sub_array (int arr [], int size) {int I = 0; // a cursor that records the original array int sum = 0; // sum to record the sum of the first k numbers (k <n) int max =-(1 <30); // max records the largest sum we have found. At first we set it to-2 ^ 31 // loop to the size position, we can find the sub-array of the sub-array, that is, Suppose {1,-2, 3, 10,-4, 7, 2} // when we set size = 4, in fact, the test array is {1,-2, 3, 10 }. While (I <size) {// This Is What we mentioned above. sum is always added to arr [I]. When sum <0, we discard sum, the number of the first k is skipped. because the number of the first k is not the optimal sub-structure, we set sum to 0 and start from the new one. Sum + = arr [I ++]; if (sum <0) {sum = 0 ;}// when sum is added with a positive number (sum new)> (original sum), while max is (original sum ). So we updated max. // When sum is added with a negative number (sum new) <(sum original), max is not updated. This is why the last number // must be greater than 0 else if (sum> max) {max = sum ;}} return max ;} // ******************* subarray start position *************** * ********* int max_starter (int arr [], int count) {// no difference between the three and the previous one int I = 0; int max =-(1 <30); int sum = 0; // What do these two mean? // Starter_final: the starting position of the largest sub-group. What about starter? // This starter records the temporary starting value, which is quite awkward. Do you want to take a look at the example? For int arr [] = {-1, 3, 5,-12, 7, 10, 3,-1} // The first starter is 2, that is, arr [1] = 3, because (arr [0] =-1) <0, sum <0, Jump directly to arr [1] and start from again, so // Let's see What starter has? A = 3, a = 7, right? Calculate by yourself. That is to say, starter records all possible start locations, and this starter_final records the starting position of the existing and largest subarrays through comparison. Int starter = 0; int starter_final = 0; while (I <count) {sum + = arr [I ++]; if (sum <0) {starter = I; sum = 0;} else if (sum> max) {max = sum; starter_final = starter ;}// we return the location. We need to add 1, that is, the position of arr [4] = 7 is 5th bits of the array. Return (starter_final + 1 );} // ********************* length of sub-array ************** * ********* int max_sub_array_length (int arr [], int count) {int max_value = 0; int starter = 0; int length = 0; max_value = max_sub_array (arr, count); starter = max_starter (arr, count)-1; while (max_value> 0) {max_value-= arr [starter ++]; ++ length;} return length ;} // *********************** all test cases ************* * ********* int main () {int arr [] = {-1, 3, 5,-12, 7, 10, 3,-1}; int a = 0; int B = 0; int c = 0; a = max_sub_array (arr, 6); B = max_starter (arr, 8); c = max_sub_array_length (arr, 5); printf ("subarray largest sum: % d \ n ", a); printf (" starting position of the sub-array: % d \ n ", B); printf (" sub-array length: % d \ n ", c); return 0 ;}
  
 

We have not completed the code here. If you want to ask, it is of course a job for everyone ~

When we get a = 1, it is a negative number, then the program will tell you the largest sum is-1073741824 (where? ). If there are still some problems, let everyone think and discover and solve them independently ~ Well, come on!


Now we have basically figured out this question. If you have any questions, please correct them and leave a message.



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.