Draw a figure!
There are 2 relevant similar right triangles.
One is outside the fence and the fence and has leg 24. The hypotenuse is 24 csc θ.
The other is between the fence and the wall and has leg 6. The hypotenuse is 6 sec θ.
The ladder length L is the sum of these 2 and the critical value will be where dL/dθ = 0.
I will leave the differentiation and algebra to you!