$\begingroup$
$\endgroup$
7
I have a long array of size $n>10^6$, call it $X$. I would like to find all ranges $[a, b)$ satisfying the following conditions
- $\sum_{i=a}^{b-1}X[i] \leq 0$,
- $b-a \geq K$,
- $\sum_{i=a-1}^{b-1} X[i] > 0$,
- $\sum_{i=a}^{b} X[i] > 0$.
I also would like to note that $X[i]$s can only take $m$ distinct values, typically $m<10$. A quadratic time algorithm is trivial. I'm wondering if I can do any better than that.
New contributor
cebir latis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
-
$\begingroup$ Can you use prefix sums to advantage? $\endgroup$greybeard– greybeard2025年11月15日 11:17:31 +00:00Commented Nov 15 at 11:17
-
1$\begingroup$ "[time] any better than [quadratic]" you may have to do an output sensitive analysis ($t = f(n) + c_2(|output|)$): there may be $O(n^2)$ such ranges/pairs. $\endgroup$greybeard– greybeard2025年11月15日 11:25:24 +00:00Commented Nov 15 at 11:25
-
$\begingroup$ Oh, got it. I think I'll have to come up with a more constrained version of 3 and 4. Thanks! $\endgroup$cebir latis– cebir latis2025年11月15日 19:18:25 +00:00Commented 2 days ago
-
$\begingroup$ Is $K$ small compared to $n$ or large? Would you be satisfied with a sub-quadratic algorithm that finds a single such interval? Do you already know of such an algorithm? $\endgroup$D.W.– D.W. ♦2025年11月15日 19:45:49 +00:00Commented 2 days ago
-
1$\begingroup$ I came up with an $O(n \log n)$ for the relaxed version I mentioned in my above comment. I'll add as an answer once I am confident. $\endgroup$cebir latis– cebir latis2025年11月16日 04:15:22 +00:00Commented 2 days ago