The Feynman inequality E(G) less-than-or-equal-to E(trial) + lim(beta) --> infinity <S - S(trial)>/beta for path integrals provides a powerful upper bound on the ground-state energy E(G) of a large variety of systems. E(trial) is the ground-state energy of some trial system with action S(trial) for imaginary values of the time variable, and S is the action (also expressed in imaginary time variables) of the system under study. beta = 1/k(B)T, where k(B) is the Boltzmann constant and T the temperature. However, the Feynman inequality is not a priori justified for a system in a magnetic field, because imaginary terms subsist in the action also after transforming to imaginary time variables. Replacing or extending this inequality when magnetic fields are present has therefore been a long-standing problem. In the present paper we solve this problem. We first derive an inequality, providing an upper bound for the ground-state energy, that is valid even in the case of a nonzero magnetic field, E(G) less-than-or-is-equal-to E(trial) + <infinity\T{U(trial)(infinity, -infinity)[V(0) - V(trial)]}\ - infinity>, for a system with Hamiltonian H0 + V. T is the time-ordering operator, and U(trial) is the time evolution operator of a trial system with Hamiltonian H0 + V(trial) in the interaction representation, with the interactions V(t) and V(trial)(t) switched on adiabatically. Because of the time ordering, retardation effects are also properly taken into account. The contribution of the magnetic field is included in the unperturbed Hamiltonian H0. If the time-dependent integrands occurring in the matrix element in the right-hand side of our generalized inequality satisfy certain analyticity conditions in the complex-time plane, this inequality reduces to the Feynman inequality for path integrals. If these analyticity conditions are not satisfied, our generalized inequality may introduce supplementary terms E(DB) in the right-hand side of the Feynman upper bound, [GRAPHICS] because different branch lines or singularities have to be taken into account in the transformation to imaginary time variables. As an important illustration, our generalized inequality is applied to the problem of the Frohlich polaron in a magnetic field. From the generalization of the Feynman inequality derived in the present paper, we determine the conditions to be imposed on the variational parameters in the trial action, such that the Feynman upper bound in its original form remains valid for a polaron in a magnetic field. Some limiting cases are studied analytically to illustrate the relevance of our additional constraints on the variational parameters of the trial system. In the free-particle limit and for a particular value of one of the variational parameters, we explicitly derive the contributions from the branch lines in the complex-time plane which arise if these additional constraints are not satisfied.