Optimality conditions for the trace of certain matrix products