I realized this is actually a 2D packing problem, because it reminds me of this Suika Game that went viral a few years ago. Intuitively, we just place the balls in a zig-zag order.

problem 222 demo

Spheres with size 30 mm, 39 mm, and 49 mm inside the tube.

Lets consider two vertically adjacent spheres with radii \(r_1\) and \(r_2\), respectively. They stack inside a tube of radius \(R\), each touching the opposite wall. The Euclidean distance between their centers is \(r_1 + r_2\), and the horizontal distance is \(2R - r_1 - r_2\). By the Pythagorean theorem, the vertical distance \(v_{1,2}\) between their centers is: \[v_{1,2}=\sqrt{(r_1+r_2)^2-(2R-r_1-r_2)^2}= 2\sqrt{R(r_1+r_2-R)}.\] The total tube height for \(n\) sphere is the sum of these vertical distances plus the top and bottom radii: \[\text{Tube Height}=r_{bottom} +\sum_{i=1}^{n-1} v_{i,i+1} + r_{top}\]

I was not entirely sure what the optimal stack order will be. So I checked all the permutations of a small subsets of spheres, and spotted the pattern.