We have designed a Halbach magnet array by using a numerical optimization method based on finite-element analysis. The magnetization direction of each element is defined as the design variable. The optimal magnet arrays composed of two and three linear magnet layers can then be investigated to increase the attractive, repulsive, and tangential magnetic forces between magnet layers. We have applied a magnet array maximizing the tangential force to a torsional spring composed of two- and three-magnet rings. The two-dimensional finite-element analysis incorporates optimization techniques such as the sequential linear programming and the adjoint variable method.