ImportRandom__author__='Administrator'LENGTH= 500Base= [] forIinchRange (0, LENGTH * 2): Base.append (Random.randint (-1 *length, length))Print(base) bsa_i=0bsa_j= 1BSA=Base[0]bord=base[0]bord_i=0 forIinchRange (1, Len (base)):ifBord <0:bord_i=I bord=Base[i]Else: Bord+=Base[i]ifBord >=bsa:bsa_i=bord_i Bsa_j= i + 1BSA=bordPrint(bsa_i, Bsa_j, BSA)Print(Base[bsa_i:bsa_j])#Verify:BSA =-1 * LENGTH-1 forIinchRange (0, Len (base)): forJinchRange (i + 1, len (base) + 1): It=0 forKinchRange (I, j): It+=Base[k]ifit >BSA:BSA=it bsa_i=I bsa_j=JPrint(bsa_i, Bsa_j, BSA)Print(Base[bsa_i:bsa_j])
When pointer I moves to the right, the maximum Subarray bord with the right boundary of I + 1 is recorded, initially bord[0, 1], and when sum bord < 0 o'clock, the left edge of the Bord is replaced by I. This method is to remove all and negative sub-arrays on the left, and the remainder is the largest subarray with the right boundary of i + 1. Correctness can be verified like this:
Contradiction
Original proposition: Bord[i, J], if there is no k belongs to [I, j] makes Sum A[i, K] <= 0, when there is no l belongs to [I, j] make Sum B[l, j] >= sum Bord[i, j].
Hypothesis: Bord[i, j], if there is no k belonging to [I, j] makes Sum A[i, K] <= 0, then exists l belongs to [I, j] makes Sum B[l, j] >= sum Bord[i, j].
If present l belongs to [I, j] makes Sum B[l, j] >= sum Bord[i, j], then sum c[i, l] = sum bord[i, j]-sum B[l, j] <= 0
If L = k, the contradiction is not established, the original proposition is correct.
The BSA array records the largest sub-array in [0, I], while border is the largest subarray of the right boundary of i + 1, and if sum border > sum BSA, Border becomes BSA. This completes the lookup of the maximum subarray of BSA for the entire array in a single traversal, the time complexity is O (n), and the subsequent verification algorithm uses the triple cyclic brute force solution with the time complexity O (n ^ 3). The complexity of the three-degree-level is almost a useless algorithm for a slightly larger n, so designing an efficient sub-array method is of great practical significance.
Algorithm Introduction Note 2-t (n) = maximum Subarray problem solution for O (n)