$\max$
and $\min$
and arithmetic operations (no if clauses), express the amount of possible overlap between two intervals $[a_1,a_2]$
and $[b_1,b_2]$
, where $a_1,a_2,b_1,b_2$
are arbitrary real numbers with $a_1<a_2$
and $b_1<b_2$
.
-
Think about intervals on the real number line. Sketch
$[a_1,a_2]$
and$[b_1,b_2]$
when these overlap? -
What is the left boundary of the overlap in terms of min/max of the 4 numbers?
-
What about the right boundary?
-
What if there is no overlap? Remember you can only use min/max functions.
-
Assume that intervals overlap, partially or fully, like in the figure above. We can notice that the smallest value in this intersection is always
$\max(a_1, b_1),$
and the largest value in this intersection is$\min(a_2,b_2).$
Hence, the amount of overlap of these intervals can be expressed as$\min(a_2,b_2)-\max(a_1, b_1).$
There will be some overlap only if this value is positive, hence the final formula is
$\max(0,\min(a_2,b_2)-\max(a_1, b_1)).$