This is the suggestion you've got in stackoverflow made more explicit:Define OPT(i,j,k,l,n) to be the maximum amount of coal you can get in $n$-steps with the condition that the last two packages that arrived to mine $X$ are i and j, and to mine $Y$ are k,l. Now, it is easy to compute OPT(i,j,k,l,n) using OPT(,,,,n-1) (just checking all the possibilities). You should be careful with the initial state (when there are less that 3 packages in some mine).
To see that the greedy does not work: Let AABBCC be the packages, the greedy assigns all the packages to X for 10 units of coal but X=ABC, Y=ABC gives you 12 units.