Solution (source code)

= Solution

Use an <orthonormal eigenbasis> of the <Hermitian operator> $A$ and set $b_j=\langle\alpha_j|B|\alpha_j\rangle$. Since $B$ is a <positive contraction>,
$$
0\leq b_j\leq1,\qquad \sum_jb_j=r,\qquad \operatorname{Tr}(AB)=\sum_j\lambda_jb_j.
$$
For $0<r<d$, the missing weight among the first $r$ entries equals the weight in the remaining entries:
$$
t:=\sum_{j<r}(1-b_j)=\sum_{j\geq r}b_j.
$$
The ordered <eigenvalues> satisfy $\lambda_j\geq\lambda_{r-1}$ for $j<r$ and $\lambda_j\leq\lambda_{r-1}$ for $j\geq r$. Therefore
$$
\sum_{j<r}\lambda_j-\operatorname{Tr}(AB)
=\sum_{j<r}\lambda_j(1-b_j)-\sum_{j\geq r}\lambda_jb_j
\geq\lambda_{r-1}t-\lambda_{r-1}t=0.
$$
This argument does not require the <eigenvalues> of $A$ to be positive. For $r=0$, positivity and zero <trace> give $B=0$; for $r=d$, the same argument applied to $I-B$ gives $B=I$. Thus \b[in every case]
$$
\boxed{\operatorname{Tr}(AB)\leq\sum_{j<r}\lambda_j.}
$$
The <orthogonal projection> onto the leading $r$ <eigenvectors> attains equality. This is the <Hermitian effect variational principle>, extending the <Ky Fan maximum principle> to all <positive contractions> with the prescribed <trace>.