In Classical Hamiltonian Mechanics, a canonical transformation of the phase-space coordinates $(p,q,t) \to (P,Q,t)$ is such that the general form of Hamilton's equations is followed and Hamilton's principle is obeyed:
$$\delta \int_{t_0}^{t_1} \left (P_i \dot{Q_i} - K (Q,P,t)\right) \, \mathrm{d}t = 0\tag{1}$$
for some new Hamiltonian $K$ just as before the transformation,
$$\delta \int_{t_0}^{t_1} \left (p_i \dot{q_i} - H (q,p,t)\right) \, \mathrm{d}t = 0\tag{2}$$
for the old Hamiltonian, $H$. Several textbooks then mention the necessary relationship between the integrands in the two equations above to be
$$\lambda (p_i \dot{q_i} - H) = P_i \dot{Q_i} - K + \frac{\mathrm d F}{\mathrm d t}.\tag{3}$$
My question is, how is the relationship above justified?