A variational characterization of flat spaces in dimension three