With Excel 365, In E3
Formula: copy to clipboard
=IF(COUNTIF($C$2:$C2,C3)>0, D3-XLOOKUP(C3,$C$2:$C2,$D$2:$D2,,0,-1),D3)
Does that work for you?