Disclaimer: The method described below is not universal, but it can often solve a problem or help you come to the right solution.
If there is a set of gaps located on some axis (usually the time axis or indices of some array) and you need to choose some of them in an optimal way so that the selected gaps do not intersect, then you should try using dynamic programming.
Approximate solution scheme:
Initially, we sort the available gaps by the right border. Let's start the following dynamics: dp[i] - the answer for the first i intervals.
We will recalculate as follows: first, consider the situation that this interval will not be used, then just dp[i] = dp[i-1]. Note that this ensures that the values of dp[i] do not decrease as i grows. And this is logical, because. adding a new gap, we cannot worsen the global answer: either we simply ignore the new gap, or we construct a more profitable variant using it. Now, if we want to use the i-th gap, then we can use those gaps whose right borders are less than the left border of the current gap, since we must choose a set of non-overlapping gaps. To do this, we initially sorted the gaps by the right border, so that now we can efficiently find the required position. This can be done analytically, if possible, but in the general case it is possible to find a gap with a binsearch, the right border of which is less than the left border of the current one and, at the same time, the maximum possible one. We want to maximize the right border for greedy reasons, because as i grows, the answer can only increase. Accordingly, we find the required position p and recalculate dp[i] through dp[p] and the i-th interval.