Try for always from max-1 to -1 in loops and write things to be efficiently.
This may include using one larger function so you reuse variables sometimes.
Try to avoid remaking same values multiple times when you don't need to.
In general, yours is good and observe fast coding techniques also.
X E.