First, let’s define the function fk(i)=ai+ai+1+⋯+ai+k−1, i.e. the sum of k consecutive months starting at i.
Now, let’s prove that if k is one answer and k≤2n, then 2⋅k is also an answer: f2k(i)=fk(i)+fk(i+k)>0. Thus we can always find an answer greater than 2n.
Then, consider the case where x≥0. If k is an answer, since fk+1(i)=fk(i)+ai+1=fk(i)+x>0, k+1 is also an answer. Thus it’s sufficient to check if k=n is the answer.
Lastly, when x<0, we need the help of the prefix sum. Define prei=a0+a1+⋯+ai−1,i>0 and pre0=0. We want to find a k such that for each 0≤i≤n−k, we have:
prei+k−preiprei>0<prei+k
Since k>2n, the numbers after the window must be x, so the formula can be rewrite as:
preiprei+x⋅(n−i)<pren−x⋅(n−k−i)<pren+x⋅k
For each i, the corresponding k is n−i, this means if the max value of the LHS is smaller than pren+x⋅(n−i), then k=n−i is a answer.