I can't say that I understand the query, and that makes it difficult to suggest improvements. The second UNION ALL with a LEFT JOIN and a RIGHT JOIN with the same tables looks mysterious to me.
But as long as you are referring to the MaxD CTE more than once, it's probably a good idea to save the result of the CTE ot a temp table.
A CTE is basically a query-scoped macro, and the parse expands the definition of the CTE to every place where it occurs. That is, it may be computed multiple times, unless the opimtizer is able to do something smart.