[Speaking algorithm small class] Use divide and conquer method to find the sum of the largest continuous subsequence

Use divide and conquer method to find the sum of the largest continuous subsequence

Set an integer sequence a[n], 1≤s, t≤n. Find a sub-sequence a[s, t] of a[n] so that the sum of the sub-sequence is as large as possible.
If this sum is less than 0, 0 is output.

[Algorithm ontology]

(In the reference code, because the running time is compared with the brute force method, the brute force method uses the prefix sum. For convenience, the array subscript starts from 1)
Set m = floor((s + t) / 2).
When n = 1, the only element is directly taken as the result. If the element is negative, 0 is output.
When n> 1, the discussion is divided into three cases:
[Case 1] The sub-sequence completely falls on the left half of the original sequence a[s, m]. Recursively find the sum of the largest continuous subsequence of the sequence a[s, m].
[Case 2] The sub-sequence completely falls on the right half of the original sequence a[m + 1, t]. Recursively find the sum of the largest continuous subsequence of the sequence a[m + 1, t].
[Case 3] This sub-sequence spans the left and right parts, so the recursive solution algorithm in [Case 1] and [Case 2] cannot find the maximum sum of such continuous sub-sequences. For this type of sub-sequence, you only need to add up each element from the midpoint m to both sides to the two ends of the sequence to obtain the maximum sum of this continuous sub-sequence.
Finally, for the sum of the consecutive subsequences obtained in the three cases, the largest one is selected as the final result.

【time complexity】

In this algorithm, if the sum of the largest continuous sub-sequence is calculated for a sequence of length n, then the left and right sub-sequences of length n / 2 need to be solved recursively, and then the recursive solution can not be taken into account across the left and right halves. Solve the sub-sequence of. So
T(1)=O(1), n=1
T(n)=2T(1/2 n)+O(n), n>1
solves T(n) = O(n log n).
Contrast with brute force algorithm:
the process of brute force algorithm is to first calculate the prefix sum of the original array (the sum of the first n items), and then use
S_n-S_(n-1)=a_n to
enumerate S_n, S_(n-1) to examine all continuous The sum of subsequences. The time complexity is O(n^2).
Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/COFACTOR/article/details/108691530