We determine the solution to the prototype problem: Given a finite amount of time, what is the optimal motion of a piston fitted to a cylinder containing a gas pumped with a given heating rate and coupled to a heat bath? The optimal motion is such as to maximize the work obtained via the piston in a specified period of time. This problem is solved for various end-point constraints, including constraints on final volume, final energy, or final volume and energy. We consider several associated problems including constraints on the rate of change of volume, piston friction, piston mass, and inertial effects of the gas. Explicit thermodynamic analyses of the solutions are carried out for various examples. The efficiency and the gain over nonoptimal paths are studied. Significant improvement over the bound on the efficiency is obtained as calculated by (infinite time, reversible) thermodynamics. The nature of the limit of the optimal solution as the time approaches infinity is determined. For a finite heating rate the optimal path is irreversible even as the time approaches infinity.