The Pointer Never Resets

a is sorted and has n elements. This is the whole loop:

int j = 0, best = 0;
for (int i = 0; i < n; i++) {
    while (j < n && a[j] - a[i] <= K) j++;
    best = max(best, j - i);
}

Counting only executions of j++, what is the worst case total across the entire run?

A

Θ(nlog⁡n)\Theta(n \log n), because j runs geometrically ahead of i.

B

At most nn, so the whole nest is Θ(n)\Theta(n).

C

About n2/2n^2/2, since the inner loop advances roughly halfway on average.

D

Exactly n2n^2: a while nested inside a for multiplies.