How to count all contiguous subsequences with positive sum? I have array $t$ with size $n \leq 10^6$. It has only two kinds of elements inside: $1$ or $-1$.
I need to count how many contiguous subsequences have positive sum.

This pseudocode demonstrates exactly the behavior I want, but is too slow for large $n$:

c = 0
for i = 1 to n do
    for i = j to n do
       if sum(u[i:j]) &gt; 0 then
           c = c + 1
return c


Partial sums can be used to optimize it, but it will still be $O(n^2)$.

Here are some examples if they help:

[-1, 1, -1, -1, -1] $\rightarrow$ 1

[1, -1, 1, 1, -1, 1] $\rightarrow$ 14

[1, 1, 1, 1, 1, 1, 1, 1, 1, 1] $\rightarrow$ 55

Does there exist linear or $n \log n$ solution?
Given the array $A_1,\ldots,A_n$, start by computing $B_i = \sum_{j \leq i} A_j$. You want to count the number of pairs $i_1 &lt; i_2$ such that $B_{i_1} &lt; B_{i_2}$, where $0 \leq i_1,i_2 \leq n$. Each such pair corresponds to a a contiguous subsequence $A_{i_1+1},\ldots,A_{i_2}$ whose sum is positive. This is the same as the classical problem of counting the number of inversions in an array (this is what you get if you reverse $B$), which can be solved in $O(n\log n)$.

It is plausible that you can do better in your case since the numbers are $\pm 1$.