Let's derive that general formula.
Instead of two objects, we have N objects each with some arbitrary temperature. We have to deal with two processes: Heat flow and performed work. The heat flow is entirely between the objects and leaves the total internal energy of the N objects together unchanged. The performed work by the system is energy that leaves the system of the N objects. Denote by U_i the total internal energy at the start and by U_f the final total internal energy, we have:
U_f = U_i - W (1)
where W is the work performed by the system of the N objects.
We can compute the internal energy in terms of the heat capacity. Although the heat capacity is assumed to be a constant, this can only be true in some limited temperature range. We'll assume that the heat capacity is constant above some temperature T0 which is smaller than the temperatures of the objects. We can then write:
U_i = N U(T0) + C(T1 - T0) +C(T2- T0) + C(T3 -T0)+...+
C(TN-T0)
Here U(T0) is the internal energy function at temperature T0, C is the heat capacity of the objects and Ti is the temperature of object i. We can rewrite (2) as:
U_i = N[U(T0) - C T0] + C (T1 + T2 + T3+...TN ) (3)
If the final temperature is T_f, then:
U_f = NU(T0) + N C (T_f - T0) =
N[U(T0) - C T0] + N C T_f (4)
We see from (1) that:
W = U_i - U_f = NC [(T1 + T2 + T3+...TN)/N - T_f] (5)
Clearly, the lower the final temperature, the more work will be performed by the system. The fact that the entropy cannot decrease imposes a limit on how low the final temprerature can be. So, if we compute the entropy of an body at temperature T, we can easily find what the maximum work is that can be extracted from the system.
We have:
dS = dQ/T
The heat capacity is a constant C for T > T0, therefore dQ = C dT for
T > T0. This gives:
dS = C dT/T
If we integrate both sides from T0 to T we get:
S(T) - S(T0) = C Log(T/T0) ------->
S(T) = S(T0) + C Log(T/T0)
The initial entropy of the system of three bodies, S_i, is thus given by:
S_i = S(T1) + S(T2) + S(T3) +...S(TN)=
N S(T0) + C[Log(T1/T0) + Log(T2/T0) + Log(T3/T0)+...Log(TN/T0)]
The final entropy, S_f, is:
S_f = N S(T_f) = N S(T0) + NC Log(T_f/T0)
If we demand that S_f >= S_i, we get:
NC Log(T_f/T0) >= C[Log(T1/T0) + Log(T2/T0) +...+ Log(TN/T0)] -->
Log(T_f/T0) >= 1/N [Log(T1/T0) + Log(T2/T0) + ...Log(TN/T0)]---->
T_f >= (T1 T2 T3 ...TN)^(1/N)
Eq. (5) then implies that:
W <= NC [Arithmetic average of initial temperatures - Geometric average of initial temperatures ]
The maximum amount of work that can be extracted is obtained in the limit of a reversible process in which the total entropy does not increase. Then, you have an equals sign in the above equation:
W = NC [Arithmetic average of initial temperatures - Geometric average of initial temperatures ]