Maximum contiguous Subarray and (maximum sub-segments and)
Question: A sequence of n integers (possibly negative numbers) a[1],a[2],a[3],..., A[n], and the maximum value of the sub-segments of the sequence, such as A[i]+a[i+1]+...+a[j], is obtained. When the given integer is negative, define the sub-segment and 0, according to this definition, the optimal value is: max{0,a[i]+a[i+1]+...+a[j]},1<=i<=j<=n
For example, when (a[1],a[2],a[3],a[4],a[5],a[6]) = ( -2,11,-4,13,-5,-2), the maximum child segment and is 20.
--Quote from "Baidu Encyclopedia"
Environment
1. Poor Lifting method
Coding
def enumerate_arrays ( Numbers): Max_sum = numbers[0 ] Num_len =
len (Numbers)
for i
in
range
(Num_len): Tmp_sum = numbers[i] max_sum = max (Tmp_sum, max_sum) for J in range (i + 1 , Num_len): Tmp_sum += number S[J] max_sum = max (Tmp_sum, max_sum) return max (0 , max_sum)
Enumerates all successive sub-arrays, summing them separately, finding the maximum sum, and the time complexity of \ (O (n^2) \)
2.Kadane algorithm
Coding
def kadane_solve(numbers): = numbers[0] =0 forin numbers: if<0: = i else: += i =max(tmp_sum, max_sum) returnmax(0, max_sum)
If the accumulated value is negative, overwrite the accumulated value with the newly read-in value, otherwise continue to accumulate with a time complexity of \ (O (n) \)
Test Cases
Coding
ImportUnitTest fromHomework.a.aImportEnumerate_arrays fromHomework.a.aImportKadane_solveclassTestA (unittest. TestCase):defTestenumerate ( Self): NUM1=[-2, One,-4, -,-5,-2] Num2=[1,2,3] Num3=[-1,-2] Num4=[1] Self. Assertequal (Enumerate_arrays (NUM1), -) Self. Assertequal (Enumerate_arrays (num2),6) Self. Assertequal (Enumerate_arrays (num3),0) Self. Assertequal (Enumerate_arrays (NUM4),1)defTestkadane ( Self): NUM1=[-2, One,-4, -,-5,-2] Num2=[1,2,3] Num3=[-1,-2] Num4=[1] Self. Assertequal (Kadane_solve (NUM1), -) Self. Assertequal (Kadane_solve (num2),6) Self. Assertequal (Kadane_solve (num3),0) Self. Assertequal (Kadane_solve (NUM4),1)if __name__ == ' __main__ ': Unittest.main ()
Use the test cases provided in the topic and all positive numbers, all negative, single number test
Test results
, the test passes
Type the command:
python -m tests.test_a
, the test passes
Software engineering Third personal job-maximum contiguous subarray and