Make a naive implementation and then improve it.
We move from left to right, calculating the partial sums, and for each position we find the leftmost partial sum, such as the current partial sum, more.
input a int partialSums[len(a)] for i in range(len(a)): partialSums[i] = (i == 0 ? 0 : partialSums[i - 1]) + a[i] if partialSums[i] > 0: answer = max(answer, i + 1) else: for j in range(i): if partialSums[i] - partialSums[j] > 0: answer = max(answer, i - j) break
This is O (n 2 ). Now, the part of finding the βbestβ sum can actually be saved through BST , where each node will be represented as a pair (partial sum, index) with a partial sum comparison. Also, each node must support a special min field, which would be the minimum indices in this subtree.
Now, instead of simply looking for a suitable partial sum, we could go down BST using the current partial sum as the key following the following three rules (assuming C is the current node, L and R are the roots of the left and right subtrees, respectively):
- Maintaining the current minimum index of βgoodβ partial sums found in
curMin is initially +β . - If
C.partial_sum is βgood,β update curMin with C.index . - If we move to
R , update curMin with L.min .
And then update the answer with i - curMin , also add the current partial amount to BST.
This will give us O (n * log n).
source share