My solution is a little bit different so you might want to check it out.

It’s very inefficient (and sort of brute force) but it works fast enough for n <= 1000.

I am not sure how much I can share about the solution here but with some logic you can solve the problem without using math, min/max approaches or even dynamic programming / memoisation.

If you struggle (as I did for at least a couple of hours), I recommend trying on paper using n=24 to figure out a solution.