The largest and

Source: Internet
Author: User

Transferred from: bytes. 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, so the output is the sum of 18 of the Child array. Without considering the time complexity, we can enumerate all sub-arrays and find their sum. However, it is a pity that the array with the length of N has O (n2), specifically N * (n + 1)/2 sub-arrays; the time complexity of finding the sum of an array whose length is n is O (n ). Therefore, the time for this idea is O (N3 ). Solution: it is easy to understand that when we add a positive number, it will increase; when we add a negative number, it will decrease. If the current sum is a negative number, the sum should be discarded and re-cleared in the following tired addition. Otherwise, the negative number will decrease the sum of the following values. Code: //////////////////////////////////////// /// find the greatest sum of all sub-Arrays
// Return value: If the input is valid, return true, otherwise return false
///////////////////////////////////////
Bool findgreatestsumofsubarray
(
Int * pdata, // an array
Unsigned int nlength, // The length of Array
Int & ngreatestsum // The greatest sum of all sub-Arrays
)
{
// If the input is invalid, return false
If (pdata = NULL) | (nlength = 0 ))
Return false;
Int ncursum = ngreatestsum = 0;
For (unsigned int I = 0; I <nlength; ++ I)
{
Ncursum + = pdata;
// If the current sum is negative, discard it
If (ncursum <0)
Ncursum = 0;

// If a greater sum is found, update the greatest sum
If (ncursum> ngreatestsum)
Ngreatestsum = ncursum;
}
// If all data are negative, find the greatest element in the array
If (ngreatestsum = 0)
{
Ngreatestsum = pdata [0];
For (unsigned int I = 1; I <nlength; ++ I)
{
If (pdata [I]> ngreatestsum)
Ngreatestsum = pdata [I];
}
}

Return true;
} Discussion: · The return value of a function is not the maximum value of the sub-array and a flag that determines whether the input is valid. If the function returns the maximum values of sub-arrays, what should be returned when a null pointer is input? Returns 0? So how do users of this function distinguish between invalid input and the maximum value of the sub-array is exactly 0? Based on this consideration, I think that the sub-array and the maximum value are put in the parameter list as a reference, and the function returns a flag indicating whether the function is executed normally.
· Special processing is required for input in special cases. When All integers in the input array are negative, the maximum value of the sub-array and the sub-array is the maximum element in the array. Solution 1: the most direct solution is, of course, to traverse, list all sub-arrays, and then calculate and. Complexity can be simply figured out: Set the two variables I and j as the boundary of the sub-array. Both variables need to traverse the entire array, and then a cursor K is required, to traverse the entire sub-array. So the total complexity is O (n ^ 3 ). The Code is as follows: 1 int maxsubsum (int * a, int N)
2 {
3 int max =-infinite;
4 int sum = 0;
5 For (INT I = 0; I <n; I ++)
6 {
7 For (Int J = I; j <n; j ++)
8 {
9 For (int K = I; k <= J; k ++)
10 {
11 sum + = A [k];
12}
13 if (sum> MAX)
14 {
15 max = sum;
16}
17}
18}
19 Return Max;
20}
21
Solution 1: After careful consideration, you will find that you do not need to use K to traverse the sub-array, because every time J moves, a new sub-array will be generated, therefore, the maximum value will not be missed every time J moves. Therefore, only I and J are moved, and the complexity is reduced to O (N ^ 2 ). The Code is as follows: 1 int maxsubsum (int * a, int N)
2 {
3 int max =-infinite;
4 int sum = 0;
5 For (INT I = 0; I <n; I ++)
6 {
7 sum = 0;
8 For (Int J = I; j <n; j ++)
9 {
10 sum + = A [J];
11 if (sum> MAX)
12 max = sum;
13}
14}
15 return Max;
16}
17
Solution 2: The splitting algorithm is similar to binary search. We can discuss whether this problem meets the condition of binary search in different situations. Case 1. All the child arrays satisfying the largest sum are in the left or right half of the current array. For example, the left half a [I]... A [n/2-1] or a [n/2] on the right... A [J]. In this case, recursive calls can be used directly. Case 2: The child array that satisfies the largest sum spans the center point of the current array. Example: A [I]... A [n/2-1] a [n/2]… A [J] continuous. In this case, you only need to search for the end of a [n/2-1] In the left half, search for two continuous arrays starting with a [n/2] In the right half to satisfy the largest and sum. Since this known starting point only requires a cursor, the complexity is 2 * O (n/2) = O (n ). Based on the above two situations, the sub-governance algorithm is recursive: T (n) = 2 T (n/2) + O (n) = O (N * logn ). The Code is as follows:
1 int maxsubsum (int * a, int left, int right)
2 {
3 //
4 int maxleftsum, maxrightsum;
5 // the maximum value of the sum of the left and right subarrays
6 int maxleftpartsum, maxrightpartsum;
7 // temporary variables used to store the calculated sum
8 int leftpartsum, rightpartsum;
9 int center, I;
10
11 // some of them have only one element
12 if (Left = right)
13 {
14 if (a [left]> 0)
15 return a [left];
16 else
17 return 0;
18}
19
20 // recursive call. Calculate the largest and subarrays of the left and right subarrays respectively.
21 // assume that the largest and subarrays are not cut by the Center
22 center = (left + right)/2;
23 maxleftsum = maxsubsum (A, left, center );
24 maxrightsum = maxsubsum (A, center + 1, right );
25
26 // assume that the largest and child arrays are cut by the Center
27 // you need to start computing from the center to both sides
28 maxleftpartsum = 0;
29 leftpartsum = 0;
30 For (I = center; I> = left; -- I)
31 {
32 leftpartsum + = A [I];
33 If (leftpartsum> maxleftpartsum)
34 maxleftpartsum = leftpartsum;
35}
36 maxrightpartsum = 0;
37 rightpartsum = 0;
38 for (I = center + 1; I <= right; ++ I)
39 {
40 rightpartsum + = A [I];
41 if (rightpartsum> maxrightpartsum)
42 maxrightpartsum = rightpartsum;
43}
44 // return the maximum value among the three.
45 return max (maxleftsum, maxrightsum), maxleftpartsum + maxrightpartsum );
46}
47
Solution 3: Let's try to observe the characteristics of this array, one element and one element. Based on whether a [0] Is In The subarray that satisfies the largest sum, we can divide it into two situations. 1. In. You can start from a [0] (relatively easy ). 2. No. This can be further divided into two situations: A [1] is not in this subarray that satisfies the largest sum. Here we can observe the characteristics of a recursion, can be a scale for N problems into the scale for N-1. Therefore, the largest and subarrays from a [0] to a [n-1] are decomposed into: 1. The subarray contains a [0]. If a [1] is not included, a [0] satisfies the conditions. In this case, max (A [0]… A [n-1]) = A [0]. If a [1] is included, max (A [0]… A [n-1]) = A [0] + max (A [1]… A [n-1]). 2. The child array does not contain a [0]. Max (A [0]... A [n-1]) = max (A [1]… A [n-1]). The final result can be the maximum value of the preceding three values, that is, Max (A [0]… A [n-1]) = max (A [0], a [0] + max (A [1]… A [n-1]), max (A [1]… A [n-1]). This complexity is linear: you only need to traverse the array once. The Code is as follows: 1 int maxsubsum (int * a, int N)
2 {
3 // assume that the sub-array satisfying the largest sum starts from startfrom [I ].
4 int * startfrom = new int [N];
5 memset (startfrom, N, 0 );
6 startfrom [n-1] = A [n-1];
7 // assume that the sum of the largest and subarrays after a [I] is longest [I] (not necessarily including a [I]).
8 int * longest = new int [N];
9 memset (longest, N, 0 );
10 longest [n-1] = A [n-1];
11
12 For (INT I = n-2; I> = 0; I --)
13 {
14 // if you start from I, either the largest and only a [I] are included, or the subsequent sequence is connected to a [I]
15 startfrom [I] = max (A [I], a [I] + startfrom [I + 1]);
16 // the largest sum, either from I or before
17 longest [I] = max (startfrom [I], longest [I + 1]);
18}
19 // the final result is saved in the number element.
20 return longest [0];
21}
22
Because of the correlation between the front and back single elements, we don't need two arrays to store this information. We only need two variables to reduce the space complexity of the program. The Code is as follows: 1 int maxsubsum (int * a, int N)
2 {
3 // assume that the child array that satisfies the largest sum is from startfrom.
4 int startfrom = A [n-1];
5 // assume that the sum of the largest and subarrays after a [I] is longest (not necessarily including a [I]).
6 int longest = A [n-1];
7
8 For (INT I = n-2; I> = 0; I --)
9 {
10 // if you start from I, either the largest and only a [I] are included, or the subsequent sequence is connected to a [I]
11 startfrom = max (A [I], a [I] + startfrom );
12 // the largest sum, either from I or before
13 longest = max (startfrom, longest );
14}
15 // the final result is saved in element 0
16 return longest;
17}
Output the starting and ending points of the subsequence, and output the sum of the subsequence and # include <stdio. h>
# Include <stdlib. h>
# Include <limits. h>
# Include <malloc. h>

Int main ()

{
Int * IP address;
Int J, length, Max, sum;
Int start1 = 0, start2 = 0;

Printf ("Please enter the array's length :");
Scanf ("% d", & length );
If (IP = (int *) malloc (length * sizeof (INT) = NULL)
{
Fprintf (stderr, "malloc memory failed! ");
Exit (1 );
}
Printf ("Enter eath element :");
For (j = 0; j <length; j ++)
Scanf ("% d", IP + J );

Max = int_min;
For (sum = J = 0; j <length; j ++)
{
Sum + = * (IP + J );
If (max <sum)
{
Start1 = start2;
Max = sum;
}
If (sum <0 ){
Start2 = J + 1;
Sum = 0;
}
}
For (j = start1, sum = 0; sum! = Max; j ++)
Sum + = * (IP + J );
Printf ("\ nthe subsequence from % d to % d, Max sum is % d \ n", start1, J-1, max );
Return 0;
}

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.