It strictly depends on gross weight, CG, temperature and winds.
The FMC (on aircraft equipped with it) will work out an optimum altitude depending on these factors + some others.
As a rule of thumb, higher altitude = thinner air + lower temperature = lower fuel burn
If the aircraft is too heavy, higher altitude = thinner air = higher angle of attack to keep level flight = higher fuel burn
of course winds play a big part in it.
That's pretty much how it works.
Usually, an airliner will do step climbs. i.e. start cruising at FL350, and then as fuel levels diminish weight decreases so 370, then 390, then 410.