I need an algorithm for real application.
Suppose we have array A (positive & negative ) numbers. we want to find index i, j such that $\sum_{k-i}^{j}{A[k]}$ has the lowest difference to zero. can anyone hint or give me a efficient algorithm or pesudocode for it?
Here is an $\mathcal{O}(n\log n)$ answer.
For example, let be A = [2, 4, 6, -9, 12, -20]. We assume zero-based indexing.
Everything except for sorting is linear. In our example we compute
After sorting, we have
Algorithm returns the absolute value of the optimal sum. One can easily modify it if he wants it to return a real sum and corresponding $i$ and $j$.