First:
Try to comprehand the algorithm without examples, if can not understand, try once again with a easy examples until know how it work(draw a process-chart) and whether it can be optimized.
Second:
According the process-char, code before finishing coming true the algorithm. In coding, if needs variables, just declare and define without thinking too much.
Third:
Checking whether the problem that out of boundary is exist and analyze the complexity of time and space.
Finally:
Getting the value of variables those you need in the codes to solve the specific problem.