The formula solution can be like this:
E2=C2 E3 and fill down=XLOOKUP(A3;$A$2:$A$6;$C$2:$C$6)-SUM(($A2:$A$2=A3)*$B2:$B$2)