Programmer programming Art: Chapter 7: finding the largest and largest continuous sub-array

Source: Internet
Author: User

Prelude

I hope that more people will treat any interview questions in this crazy comedy series as a simple programming question or a substantive question like me, in the course of reading this crazy series, I hope you can put all the burdens related to the interview as much as possible, and devote yourself to solving every "programming question". In the process of solving programming questions, enjoy the unlimited fun of programming and the unlimited passion of thinking. -- By @ July _____.
The original fantasy series has been renamed as the programmer programming Art series. The original fantasy group was renamed as the programming art room. The art of programming room is dedicated to the following three tasks: 1. To address a problem, we constantly seek more efficient algorithms and implement them through programming. 2. solve practical application problems, such as chapter 10, how to sort disk files with 10 ^ 7 data volumes. 3. Research and Implementation of classical algorithms. Overall highlights: programming, how to efficiently program to solve practical problems. You are welcome to join us.

Section 1: Calculate the largest sum of sub-Arrays
3. Obtain the largest sum of sub-Arrays
Description:
Enter an integer array, and the array contains positive and negative numbers.
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 maximum sub-array is 3, 10,-4, 7, 2,
Therefore, the output is the sum of 18 of the sub-array.

Analysis: this problem occurs frequently during interviews with major companies and is cited many times. Non-General interview questions can be matched. With this alone, there is no reason not to be included in the fantasy series. This was one of the 100 questions of Microsoft's 3rd questions that I have previously compiled. So far, this question has received a lot of attention. OK. Next, let's analyze this question step by step:
1. Obtain the largest sub-array and of an array, so that the sequence 1,-2, 3, 10,-4, 7, 2,-5, I think the most intuitive and brutal way is to traverse three layers of the for Loop, find the sum of each sub-array in the array, and finally find the maximum value of these sub-arrays.
Sum [I ,..., J] represents the Sum (0 <= I <= j <n) between the I-th element and the j-th element in array A, traversing all possible Sum [I ,..., J], so the time complexity is O (N ^ 3 ):

// This code is introduced from the beauty of Programming
Int MaxSum (int * A, int n)
{
Int maximum =-INF;
Int sum = 0;
For (int I = 0; I <n; I ++)
{
For (int j = I; j <n; j ++)
{
For (int k = I; k <= j; k ++)
{
Sum + = A [k];
}
If (sum> maximum)
Maximum = sum;

Sum = 0; // remember to reset the value here. Otherwise, sum will eventually store the sum of all sub-arrays. That is, the bug mentioned in the beauty of programming. Thank you, Wolf.
}
}
Return maximum;
}

2. In fact, the following O (N) algorithm is directly provided for the Microsoft 100 Question and Answer V0.2 [answer to Question 1-20] I uploaded earlier:
View plaincopy to clipboardprint?
// Copyright @ July 2010/10/18
// Updated, 2011.05.25.
# Include <iostream. h>

Int maxSum (int * a, int n)
{
Int sum = 0;
// In fact, it is very easy to handle all negative numbers. As you can see at, change this sentence to "int sum = a [0 ]".
// You can also leave it unchanged. If all values are negative, 0 is returned directly, which is not necessarily the case.
Int B = 0;

For (int I = 0; I <n; I ++)
{
If (B <0 )//...
B = a [I];
Else
B + = a [I];
If (sum <B)
Sum = B;
}
Return sum;
}

Int main ()
{
Int a [10] = {1,-2, 3, 10,-4, 7, 2,-5 };
// Int a [] = {-1,-2,-3,-4}; // use case where all tests are negative.
Cout <maxSum (a, 8) <endl;
Return 0;
}

/*-------------------------------------
Explanation:
For example, the input array is 1,-2, 3, 10,-4, 7, 2,-5,
The largest sub-array is 3, 10,-4, 7, 2,
Therefore, the output is the sum of 18 of the sub-array.
 
Everything is in the following two lines,
That is:
B: 0 1-1 3 13 9 16 18 13
Sum: 0 1 1 3 13 13 16 18 18

In fact, the algorithm is very simple. After adding up the current number, after B <0,
Assign B a value again and set it to the next element, B = a [I].
When B> sum, sum = B is updated;
If B <sum, sum is the original value and is not updated .. July and 10/31.
----------------------------------*/

3. After seeing the answer above, many of my friends thought that the code of idea 2 above did not handle all negative numbers. When it was all negative, we could let the program return 0, you can also let it return the largest negative number. The following code is rewritten in the previous few days. The modified code is used to handle all negative values (return the largest negative number:

View plaincopy to clipboardprint?
// Copyright @ July
// July, updated, 2011.05.25.
# Include <iostream. h>
# Define n 4 // define a variable

Int maxsum (int a [n])
// Here, you can see the advantages of the above idea 2 code (pointer)
{
Int max = a [0]; // The maximum number of returned values.
Int sum = 0;
For (int j = 0; j <n; j ++)
{
If (sum> = 0) // if an element is added, sum> = 0
Sum + = a [j];
Else
Sum = a [j]; // If an element is added, sum <0 will not be added.
If (sum> max)
Max = sum;
}
Return max;
}

Int main ()
{
Int a [] = {-1,-2,-3,-4 };
Cout <maxsum (a) <endl;
Return 0;
}
4. Specific equation of the DP Solution: @ flyinghearts: set sum [I] to the first I element, which contains the I-th element and the largest continuous subarray, result is the largest of the Child arrays that have been found. There are two options for the I + 1 element: As the first element of the new sub-array, and put it into the sub-array found above.
Sum [I + 1] = max (a [I + 1], sum [I] + a [I + 1])
Result = max (result, sum [I])
 

Extension:
1. If the array is a two-dimensional array, do you also need to calculate the sum of the largest sub-array and column?
2. If you want to obtain the maximum product column of the Child array?
3. If both the start and end columns of the Child segment are required to be output?

Section 2 Data structures and Algorithm analysis in C

The following are four implementations in Data structures and Algorithm analysis in C.

View plaincopy to clipboardprint?
// Thanks to firo
// July, 2010.06.05.

// Algorithm 1: The time efficiency is O (n * n)
Int MaxSubsequenceSum1 (const int A [], int N)
{
Int ThisSum = 0, MaxSum = 0, I, j, k;
For (I = 0; I <N; I ++)
For (j = I; j <N; j ++)
{
ThisSum = 0;
For (k = I; k <j; k ++)
ThisSum + = A [k];

If (ThisSum> MaxSum)
MaxSum = ThisSum;
}
& N

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.