I teach the dumb class in HS, and I can’t actually answer this question. The explanations online make my eyes kind of glaze over. Can anyone put this in English for someone who only went through Calc 1 and Organic?
The basic, but not particularly satisfying, answer is that sometimes electrons in a 3d orbital are lower energy than electrons in a 4s orbital, and sometimes electrons in a 3d orbital are higher energy than electrons in a 4s orbital. It all depends on the configuration of the atom in question (charge of the nucleus, configuration of the electrons, etc…).
Empty 3d and 4s orbitals have energy levels that are rather close together, and small changes in an atom’s configuration can tip the balance. Oversimplifying a bit, there are two competing parameters, effective nuclear charge and principal quantum number. Based on principal quantum number, a 3d orbital should, in general, have lower energy than a 4s orbital. However, the effective nuclear charge felt by an electron in a 4s orbital should, in general, be greater than that felt by a 3d. And so a based on effective nuclear charge, a 4s electron should be more strongly attracted to the nucleus, and the 4s orbital should have a lower energy than a 3d orbital.
Because of these two competing factors, what winds up happening is that for K and Ca, 4s is lower. But as more protons and electrons are added, the shielding effects of the additional electrons lower the effective nuclear charge felt by the last of the added electrons overall, such that some of the 3d orbitals become lower in energy and are filled before 4s.
It’s just the way the quantum mechanical math works out.
Or to put it more simply: Energy depends on all of the quantum numbers. It depends most strongly on n, but it still depends on all the others, too. And if those quantum numbers are large enough, the difference in some other number can be more significant than a small difference in n.
Of course, if you want to know exactly how energy depends on all of the various quantum numbers, and derive the formulas, then you need quantum mechanics. But that’s the gist of it.