Need some help adjusting the following games behind formula to re-calculate after the year changes based on the data located in my table.

The data is sorted by the year (column A), team name (column B), Wins (Column C), Losses (Column D), and Games Behind in Column (K).

I’m having difficulties when the year (Column A) changes.
The formula is set up to calculate based of the max for all years. I need to adjust the formula to base off each individual year. Therefore, I need to adjust the Max/Min for each year to start over when the year changes.

=IF(AND(A2=A1),((MAX(D )-D2)+(E2-MIN(E:E)))/2,0)

I appreciate any help you can give.