Topic:
An array of length n and a sub-array of the nearest 0.
Ideas:
For an array a, its sub-arrays and the nearest 0 will only appear in two cases:
- Array subscript from 0 to I
- Array subscript from I to J
(where i,j are less than the array length)
How to do?
- For the first case, just ask for the array a from 0 with a.length all the previous I items and then find the smallest.
- For the second case, we first find all the first I items in 1 and then the order from small to large, and finally subtract the sorted first and 22, the lowest difference
- Finally, the smallest of the 1 and 22 cases can be returned.
Apply for the same length of space sum[0 ... N-1],sum[i] is the former I of a and.
? Trick: definition sum[-1] = 0
? Obviously there are:
? Algorithm:
? To sum[0 ... N-1], and then calculates the difference between the sum of adjacent elements, and the minimum value is recorded as Min1.
? Min1: Arbitrarily fetching two sets in a, the minimum value of the respective element and the difference
? Because sum[-1]=0,sum[0 ... N-1] The absolute minimum value is recorded as Min2.
? The minimum value of the sum of the first k elements of a min2:a
? The smaller of the min1 and the min2, is the request.
The calculation of the sum itself and the calculation of the adjacent element difference are all O (N), the sort of sum is O (NLOGN), therefore, the total time complexity: O (NLOGN)
Emphasis: In addition to the minimum value for calculating the difference of the sum adjacent elements, do not forget the minimum value of the sum itself. A corresponding A[I...J], a corresponding A[0...J]
1 " "2 0 and array3 " "4 5 6 defsums (a):7n =Len (a)8sums = [0] * (n + 1)9 forIinchRange (0, N):TenSums[i + 1] = Sums[i] +A[i] One returnSorted ((sums[1:])) A - - defdiff (a): then =Len (a) -D = [0] * (n-1) - forIinchRange (1, N): -D[I-1] = a[i]-a[i-1] + returnmin (d) - + A defMain (a): atA_sums =sums (a) -Min_diff =diff (A_sums) - returnmin (min_diff, min (a_sums)) - -Test = [10, 14, 2, 3,-4] - Print(Main (test))
0 and array