Optimizing for maximum intervals given a distance bound
A simple double pointer $O(n)$ linear scan suffices. Initialize $i = j = 1$.


Increment $j$ until the next step would make $e_j - s_i &gt; b$. Check if $j - i$ is better than the best found result, if yes, store $(i, j)$ (the boundaries of your subset).
Increment $i$. Terminate if we reached the end of the set.


The key observation here is that if a certain $j$ for $i$ is optimal, then for $i' = i+1$, it must be that $j' \geq j$, so we only ever have to scan forwards.