Mechanical and phononic metamaterials exhibiting negative elastic moduli, gapped vibrational spectra, or topologically protected modes enable precise control of structural and acoustic functionalities. While much progress has been made in their experimental and theoretical characterization, the inverse design of mechanical metamaterials with arbitrarily programmable spectral properties and mode localization remains an unsolved problem. Here, we present a flexible computational inverse-design framework that allows the efficient tuning of one or more gaps at nearly arbitrary positions in the spectrum of discrete phononic metamaterial structures. The underlying algorithm optimizes the linear response of elastic networks directly, is applicable to ordered and disordered structures, scales efficiently in 2D and 3D, and can be combined with a wide range of numerical optimization schemes. We illustrate the broad practical potential of this approach by designing mechanical bandgap switches that open and close pre-programmed spectral gaps in response to an externally applied stimulus such as shear or compression. We further show that the designed structures can host topologically protected edge modes, and validate the numerical predictions through explicit 3D finite element simulations of continuum elastica with experimentally relevant material parameters. Generally, this network-based inverse design paradigm offers a direct pathway towards manufacturing phononic metamaterials, DNA origami structures and topolectric circuits that can realize a wide range of static and dynamic target functionalities. arXiv:1802.07214v2 [cond-mat.mtrl-sci]