We consider a linear consensus problem with time-varying connectivity modeled as a switched system, switching between two linear consensus subsystems. A natural question is which switching law yields the best (or worst) consensus convergence rate? We formalize this question in the framework of optimal control theory. The linear switched system is relaxed to a bilinear control system, with the control replacing the switching law. A control is said to be optimal if it leads to the best convergence to consensus. We derive a necessary condition for optimality, stated in the form of a maximum principle (MP). We give a complete characterization of the optimal control in the two-dimensional case, while in the three-dimensional case we show that there is always an optimal control that belongs to a subset of "nice" controls. Higher-dimensional systems may be addressed using efficient numerical algorithms for solving optimal control problems.