The Markgrafenschloß was built between 1704 and 1738. Its gardens continued to be a notable attraction into the 19th century. In 1791, the last margrave sold his realm to the Kingdom of Prussia. In 1796, the Duke of Zweibrücken, Maximilian Joseph — the future Bavarian king Max I Joseph — was exiled to Ansbach after Zweibrücken had been taken by the French. In Ansbach, Maximilian von Montgelas wrote an elaborate concept for the future political organization of Bavaria, which is known as the Ansbacher Mémoire. Napoleon forced Prussia to cede Ansbach and its principality to Bavaria in the Franco-Prussian treaty of alliance signed at Schönbrunn Palace on 15 December 1805 at the end of the Third Coalition. The act was confirmed by the 1815 Congress of Vienna; Prussia was compensated with the Bavarian duchy of Berg. Ansbach became the capital of the circle of Middle Franconia following the unification of Germany; at the time, it had a population of 12,635.