Physiological levels of oxygen and carbon dioxide in the blood are tightly regulated by varying the pattern of breathing, but this can be achieved with different combinations of amplitude and frequency. Why a specific combination of amplitude and frequency of breathing is observed remains a mystery. The aim of this study is to explore the hypothesis that the particular combination realised is optimal with respect to some objective function. Several objective functions have been suggested in the literature, such as the rate of work during inhalation, the average force exerted by the respiratory muscles, and the weighted sum of volumetric acceleration and work during inhalation; all of these objective functions provide physiologically acceptable minima under normal conditions. Resolving this issue requires optimal solutions of mathematical models that reflect more accurately the complex interaction between lung mechanics and gas exchange, but this in turn requires the development of new computational methodologies. To help achieve this goal, we constructed a simple mathematical model, consisting of two piecewise linear differential equations, that mimics gas exchange in the lungs. By using concepts from optimal control theory, we found the necessary conditions that minimise a given objective function subject to several constraints, such as satisfying the differential equations and maintaining one of the variables at a given average value. We could then solve the optimal control problem both analytically and numerically. Our method can be extended to models with higher dimensions.